.NET Manual Reset Event

In the code below, the main function is awaiting the installation of a Manual Reset Event (mre). However, before the wait starts , the synchronization object is already configured for the signaling state by another thread.

So, is it safe to wait for “already signaled synchronization 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"); } } 
+4
source share
2 answers

Yes. If it is already signaled, there will be no expectations. It's fine.

In fact, if you look at the returned value of WaitOne(int) , you will see that it returns true if it is already set (or set before the timeout), and false if it does not set the value within your timeout value.

This difference is sometimes important, so keep in mind that there is a return value.

+5
source

Yes, the code just continues.

0
source

All Articles