Alex Rivera | Logout

What is the difference between Thread.Sleep(timeout) and ManualResetEvent.Wait(timeout)?

Asked 2010-06-08T16:06:45.880
17

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

Edit
Report

1 Answer

5

The Sleep() function hasn't worked this way for a long time. Its accuracy is determined by the multimedia timer period, something you can change by P/Invoking timeBeginPeriod(). Unfortunately, on my machine I've got some kind of program that sets this period to one millisecond, making sleeps accurate down to a millisecond. Here's some code to try for yourself:

using System;
using System.Diagnostics;
using System.Threading;
using System.Runtime.InteropServices;

class Program {
    static void Main(string[] args) {
        //timeBeginPeriod(1);
        var sw1 = Stopwatch.StartNew();
        for (int ix = 0; ix < 100; ++ix) Thread.Sleep(10);
        sw1.Stop();
        var sw2 = Stopwatch.StartNew();
        var mre = new ManualResetEvent(false);
        for (int ix = 0; ix < 100; ++ix) mre.WaitOne(10);
        sw1.Stop();
        Console.WriteLine("Sleep: {0}, Wait: {1}", sw1.ElapsedMilliseconds, sw2.ElapsedMilliseconds);
        Console.ReadLine();
        //timeEndPeriod(1);
    }
    [DllImport("winmm.dll")]
    private static extern int timeBeginPeriod(int period);
    [DllImport("winmm.dll")]
    private static extern int timeEndPeriod(int period);
}

Output on my machine:

Sleep: 999, Wait: 1003

with a variability of about 5 milliseconds.

answered 2010-06-08T17:09:59.183

Your Answer