ManualResetEvent usage, manualresetevent
1. Brief Introduction
ManualResetEvent allows threads to communicate with each other by sending signals. Generally, this communication involves the tasks that a thread must complete before other threads perform. When a thread starts an activity (this activity must be completed before other threads can start), it calls Reset to put ManualResetEvent in a non-terminating State, which can be considered to control ManualResetEvent. The thread that calls WaitOne on ManualResetEvent will stop and wait for the signal.
When the control thread completes the activity, it calls Set to send a signal waiting for the thread to continue. And release all the waiting threads. Once it is terminated, ManualResetEvent will remain terminated (that is, the thread that calls WaitOne will return immediately and will not block it) until it is manually reset. You can pass a Boolean value to the constructor to control the initial status of ManualResetEvent,
True if the initial status is terminated; otherwise, false.
Second, code demonstration
Using System; using System. collections. generic; using System. linq; using System. text; using System. threading; using System. threading. tasks; namespace ConsoleApplication2 {class MyThread {Thread t = null; ManualResetEvent manualEvent = new ManualResetEvent (true); // It is trur. You can Run private void Run () at the beginning () {while (true) {this. manualEvent. waitOne (); Console. writeLine ("Thread id: {0}", Thread. currentThread. managedThrea DId); Thread. sleep (2000) ;}} public void Start () {this. manualEvent. set ();} public void Stop () {this. manualEvent. reset ();} public MyThread () {t = new Thread (this. run); t. start () ;}} class Program {static void Main (string [] args) {MyThread myt = new MyThread (); while (true) {Console. writeLine ("Enter the stop background thread to suspend start and start execution! "); String str = Console. readLine (); if (str. toLower (). trim () = "stop") {Console. writeLine ("the thread stops running... \ n "); myt. stop ();} if (str. toLower (). trim () = "start") {Console. writeLine ("the thread starts running... \ n "); myt. start ();}}}}}
Test result