This article is mainly for everyone to introduce the ManualResetEvent use method, with a certain reference value, interested in small partners can refer to
The example of this article for everyone to share the use of ManualResetEvent, for your reference, the specific content as follows
1. Source code Download:
Demo:
2. ManualResetEvent detailed
ManualResetEvent allows threads to communicate with each other by signaling. Typically, this communication involves a task that a thread must complete before other threads are made. 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 a control ManualResetEvent. A thread that calls WaitOne on ManualResetEvent will block and wait for the signal. When the control thread finishes the activity, it calls Set to emit a signal that the waiting thread can continue. And frees all waiting threads. Once it is terminated, ManualResetEvent will remain signaled (that is, the thread of the call to WaitOne will return immediately, not block) until it is manually reset. You can control the initial state of a ManualResetEvent by passing a Boolean value to the constructor, true if the initial state is signaled, or false if it is in the terminating state.
using system;using system.collections.generic;using system.linq;using System.Text;using System.Threading; Namespace Manualreseteventdemo{class Mredemo {private ManualResetEvent _mre; Public Mredemo () {this._mre = new ManualResetEvent (true); public void Createthreads () {Thread T1 = new Thread (new ThreadStart (Run)); T1. Start (); Thread t2 = new Thread (new ThreadStart (Run)); T2. Start (); } public void Set () {This._mre. Set (); } public void Reset () {This._mre. Reset (); private void Run () {string strthreadid = string. Empty; try {while (true) {//blocks the current thread this._mre. WaitOne (); Strthreadid = Thread.CurrentThread.ManagedThreadId.ToString (); Console.WriteLine ("Thread (" + Strthreadid + ") is running ..."); Thread.Sleep (5000); }} catch (Exception ex) {Console.WriteLine ("Thread (" + Strthreadid + ") exception occurred! Error description: "+ ex." Message.tostring ()); } } }}
using system;using system.collections.generic;using system.linq;using System.Text; Namespace manualreseteventdemo{class Program {static void Main (string[] args) {Console.WriteLine ("***************** ***********"); Console.WriteLine ("Input \" stop\ "Stop thread Run ..."); Console.WriteLine ("Input \" run\ "Open thread Run ..."); Console.WriteLine ("****************************\r\n"); Mredemo Objmre = new Mredemo (); Objmre.createthreads (); while (true) {string input = Console.ReadLine (); if (input. Trim (). ToLower () = = "Stop") {Console.WriteLine ("Thread has stopped running ..."); Objmre.reset (); } else if (input. Trim (). ToLower () = = "Run") {Console.WriteLine ("Thread Open Run ..."); Objmre.set (); } } } }}