Use ManualResetEvent to control the suspend and resume of the printed thread of an asynchronous call
The printing process can be long, and it may take a pause to do something and then come back and continue printing
There are 2 threads in the printing process: One is the main thread of the program running, one is the print thread that is called asynchronously, and the control that needs to be implemented is the control in the main thread (pausing the Print button) for controlling the print thread
Pause and resume.
ManualResetEvent is like a semaphore, when there is a signal (either initialized to True or the set () method called by the thread thread) represents all the threads Waiting (WaitOne ()), you can
Continues to run, when there is no signal (either initialized to False or the reset () method called by the thread thread) represents all the threads waiting, you continue to wait
Here is the example code:
The program starts with a signal, so that when you click the Print button, you can print directly
static ManualResetEvent mre = new ManualResetEvent (true);
private void Btnprint_click (object sender, EventArgs e)
{
Asynchronously invokes the Print method in the Print button event, looping the print
There is a MRE in the print loop body. WaitOne (); When the signal is signaled, continue.
When the signal is not signaled, it pauses.
}
To control whether to continue printing or to pause printing by setting the semaphore with and without control in the button event that controls pause and continue
private void Btnstopprint_click (object sender, EventArgs e)
{
if (Btnstopprint.text = = "Pause print") {
MRe. Reset ();
Btnstopprint.text = "Continue printing";
}
else if (Btnstopprint.text = = "Continue printing") {
MRe. Set ();
Btnstopprint.text = "Pause printing";
}
}
There is also a aotoresetevent and ManualResetEvent similar, just one is automatic, one is manual. Aotoresetevent only allows one thread to get a signal,
When a thread obtains the signal, the aotoresetevent will automatically reset () to No signal
Use ManualResetEvent to control the suspend and resume of the printed thread of an asynchronous call (GO)