ManualResetEvent WaitOne(timeout) returns early. Any ideas why?

房东的猫 提交于 2021-02-07 20:18:10

问题


I'm using the ManualResetEvent WaitOne(timeout) method and set the timeout value to 30ms.

I log using log4net at either side of the WaitOne. The log messages show the WaitOne returned false after only waiting for 22ms. What would cause this? A .Net bug?

Thanks in advance.


回答1:


From the Win32 documentation on Wait Functions which the .NET methods ultimately use (http://msdn.microsoft.com/en-us/library/ms687069.aspx):

Wait Functions and Time-out Intervals

The accuracy of the specified time-out interval depends on the resolution of the system clock. The system clock "ticks" at a constant rate. If the time-out interval is less than the resolution of the system clock, the wait may time out in less than the specified length of time. If the time-out interval is greater than one tick but less than two, the wait can be anywhere between one and two ticks, and so on.




回答2:


Either the event is signaled early, or you have timer inaccuracy playing a role in this, since the system clock is, by default, accurate to only 15.625 ms.




回答3:


In general, don't depend on timeouts to be exact. They'll be approximately correct, not not necessarily perfect. For the same reason, you shouldn't be depending on calls like Thread.Sleep() for timing, the OS doesn't ensure that these calls are timed exactly




回答4:


Internally, the WaitOne method from .NET calls the Windows WaitOne method. This is not a bug but normal Windows behavior.



来源:https://stackoverflow.com/questions/3961795/manualresetevent-waitonetimeout-returns-early-any-ideas-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!