C # multithreading 7-collaboration between threads ManualResetEvent,
ManualResetEvent: a manual reset event. It is easy to understand and use for inter-thread synchronization.
private static void MultiThreadSynergicWithManualResetEvent() { ManualResetEvent mre = new ManualResetEvent(false); Thread thread1 = new Thread(() => { mre.WaitOne(); mre.Reset(); Console.WriteLine("thread1 work"); mre.Set(); Thread.Sleep(1000); }); thread1.Start(); Thread thread2 = new Thread(() => { mre.WaitOne(); Console.WriteLine("thread2 work"); Thread.Sleep(1000); }); thread2.Start(); mre.Set(); }
Note:
1. ManualResetEvent mre = new ManualResetEvent (false) to create a manual reset event. The value of initialState is false, indicating whether to automatically send a reset event notification after creation. false indicates not to automatically send a reset event notification.
2. After the thread starts, run mre. Set () to send a mre notification to the thread that needs to notify the event.
3. The internal mre. WaitOne () indicates that the thread can continue to run only after the arrival of the mre notification. The thread is in the waiting state.
4. mre in the thread. waitOne () followed by mre. reset () indicates the thread that calls the Reset to terminate the notification after receiving the mre notification. Which thread executes the mre first. reset (), which exclusively occupies the notification.
5. The mre. Set () inside the thread. After the thread executes the necessary functions, it starts the notification again and passes it down (downstream transmission is an image metaphor for friends to understand)