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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With