Thread.Sleep 小于 1 毫秒 [英] Thread.Sleep for less than 1 millisecond

查看:28
本文介绍了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 毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆