Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Manual Reset Event

In the code below, Main function waits for Manual Reset Event (mre) to be set. However, before the waiting starts, the sync object is already set to signaled state by other thread.

So, is it safe to wait for "already signaled sync objects"?

class Program
{
    static void Main(string[] args)
    {
        ManualResetEvent mre = new ManualResetEvent(false);
        ThreadPool.QueueUserWorkItem(new WaitCallback(Func), mre);
        Thread.Sleep(1500);
        mre.WaitOne(100000); // Waiting for already signaled object
        Console.WriteLine("Wait Completed");
    }

    public static void Func(object state)
    {
        ManualResetEvent mre = (ManualResetEvent)state;
        mre.Set();
        Console.WriteLine("Mre Is Set");
    }
}
like image 273
Ahmet Altun Avatar asked Jun 13 '12 10:06

Ahmet Altun


1 Answers

Yes. If it's already signalled, there won't be any waiting done. That's fine.

In fact, if you look at the return value of WaitOne(int) you'll see that it returns true if it is already set (or gets set before the timeout), and false if it doesn't get set within your timeout value.

That distinction is sometimes important so be aware that there is a return value.

like image 50
jglouie Avatar answered Sep 18 '22 12:09

jglouie