The difference between ManualResetEvent and AutoResetEvent. autoreseteventreset
Before discussing this issue, we should first understand the idea that communication between threads is through sending signals. (This is not nonsense)
First, we will discuss ManualResetEvent. During the discussion, I will introduce some AutoResetEvent content for comparison:
ManualResetEvent can block one or more threads until you receive a signal to tell ManualResetEvent not to block the current thread.
It can be imagined that the ManualResetEvent object has a Boolean type attribute IsRelease to control whether to block the current thread. We can set this attribute during initialization, such as ManualResetEvent event = new ManualResetEvent (false). This indicates that the default attribute is to block the current thread.
Code example:
ManualResetEvent _ manualResetEvent = new ManualResetEvent (false );
Private void BT_Temp_Click (object sender, RoutedEventArgs e)
{
Thread t1 = new Thread (this. Thread1Foo );
T1.Start (); // start thread 1
Thread t2 = new Thread (this. Thread2Foo );
T2.Start (); // start thread 2
Thread. Sleep (3000); // Sleep the current main Thread, that is, the Thread that calls BT_Temp_Click
_ ManualResetEvent. Set (); // Set IsRelease to True.
}
Void Thread1Foo ()
{
_ ManualResetEvent. WaitOne ();
// Block thread 1 until the main thread sends a signal to thread 1 and notifies _ menuResetEvent that your IsRelease attribute is already true,
// Thread 1 is no longer blocked at this time, and the program continues to run
MessageBox. Show ("t1 end ");
}
Void Thread2Foo ()
{
_ ManualResetEvent. WaitOne ();
// Block thread 2 until the main thread sends a signal to thread 1 and notifies _ menuResetEvent that your IsRelease attribute is already true,
// Thread 2 is no longer blocked at this time, and the program continues to run
MessageBox. Show ("t2 end ");
}
Note the following important differences between ManualResetEvent and AutoResetEvent:
Manual will certainly send a signal to both thread 1 and thread 2, while auto will only send a random signal to one of them.
Why is it manual and auto? I think this is a question for many people. Now let's look at this question.
I think everyone understands this sentence of _ manualResetEvent. Set (); just now. It can be seen as setting the attribute of IsRelease to true. In thread 1
_ ManualResetEvent. WaitOne (); thread 1 is no longer blocked after receiving the signal. The IsRelease value is true in the subsequent process. If
To return the IsRelease value to false, you must call the _ manualResetEvent. Reset () method.
If it is _ autoResetEvent. set (), the value of IsRelease is automatically set to false after _ autoResetEvent. WaitOne.
This is why one is called auto and the other is manual.
Original link http://www.2cto.com/kf/201007/52946.html