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");
}
}
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 returnstrueif it is already set (or gets set before the timeout), andfalseif it doesn’t get set within your timeout value.That distinction is sometimes important so be aware that there is a return value.