Thread.Sleep 小于 1 毫秒

编程入门 行业动态 更新时间:2024-10-08 04:23:41
本文介绍了Thread.Sleep 小于 1 毫秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在不到 1 毫秒的时间内调用线程睡眠.我读到 thread.Sleep 和 Windows-OS 都不支持.

I want to call thread sleep with less than 1 millisecond. I read that neither thread.Sleep nor Windows-OS support that.

有什么解决办法?

对于那些想知道我为什么需要这个的人:我正在做压力测试,想知道我的模块每秒可以处理多少消息.所以我的代码是:

For all those who wonder why I need this: I'm doing a stress test, and want to know how many messages my module can handle per second. So my code is:

// Set the relative part of Second hat will be allocated for each message //For example: 5 messages - every message will get 200 miliseconds var quantum = 1000 / numOfMessages; for (var i = 0; i < numOfMessages; i++) { _bus.Publish(new MyMessage()); if (rate != 0) Thread.Sleep(quantum); }

我很乐意听取您的意见.

I'll be glad to get your opinion on that.

推荐答案

你不能这样做.单个睡眠调用通常会阻塞超过一毫秒(这取决于操作系统和系统,但根据我的经验,Thread.Sleep(1) 往往会阻塞 12-15 毫秒).

You can't do this. A single sleep call will typically block for far longer than a millisecond (it's OS and system dependent, but in my experience, Thread.Sleep(1) tends to block for somewhere between 12-15ms).

通常,Windows 并非设计为实时操作系统.这种类型的控制通常无法在普通(桌面/服务器)版本的 Windows 上实现.

Windows, in general, is not designed as a real-time operating system. This type of control is typically impossible to achieve on normal (desktop/server) versions of Windows.

最接近的通常是旋转并消耗 CPU 周期,直到达到所需的等待时间(使用高性能计数器测量).然而,这非常糟糕 - 你会吃掉整个 CPU,即使那样,你也可能会得到 有时会被操作系统抢占并且有效地休眠"超过 1 毫秒...

The closest you can get is typically to spin and eat CPU cycles until you've achieved the wait time you want (measured with a high performance counter). This, however, is pretty awful - you'll eat up an entire CPU, and even then, you'll likely get preempted by the OS at times and effectively "sleep" for longer than 1ms...

更多推荐

Thread.Sleep 小于 1 毫秒

本文发布于:2023-05-31 14:00:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/393022.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Thread   Sleep

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!