Both Thread.Sleep(timeout) and resetEvent.Wait(timeout) cause execution to pause for at least timeout
milliseconds, so is there a difference between them? I know that Thread.Sleep causes the thread to give up the remainder of its time slice, thus possibly resulting in a sleep that lasts far longer than asked for. Does the Wait(timeout) method of a ManualResetEvent object have the same problem?
Edit: I'm aware that a ManualResetEvent's main point is to be signaled from another thread - right now I'm only concerned with the case of an event's Wait method with a timeout specified, and no other callers setting the event. I want to know whether it's more reliable to awaken on-time than Thread.Sleep
Thread.Sleep(timeout)
causes an unconditional wait before execution is resumed. resetEvent.WaitOne(timeout)
causes the thread to wait until either (1) the event is triggered, or (2) the timeout is reached.
The point of using events is to trigger them from another thread, so you can directly control when the thread wakes up. If you don't need this, you shouldn't be using event objects.
EDIT: Timing-wise, they are both equally reliable. However, your comment about "awakening on time" worries me. Why do you need your code to wake up on time? Sleep
and WaitOne
aren't really designed with precision in mind.
Only if timeout
is below 50ms or so and you need the reliability, you should look into alternate methods of timing. This article looks like a pretty good overview.