Following the example, the code is slightly changed and typed, as shown below
Using system;using system.collections.generic;using system.linq;using system.threading;using System.Threading.Tasks Using System.text;namespace demo2{class Program {static void Main (string[] args) {const int taskcount = 10; Event array, logging thread execution status var mevents = new Manualreseteventslim[taskcount]; Wait for array, receive event signal from var waithandles = new Waithandle[taskcount]; Classes that perform specific tasks var Calcs = new Calculator[taskcount]; Task Factory TaskFactory tf = new TaskFactory (); for (int i = 0; i < Taskcount; i++) {//Initialize event Mevents[i] = new Manualreseteven Tslim (FALSE); Bind event with wait binding waithandles[i] = Mevents[i]. WaitHandle; Initializes the class that performs the task calcs[i] = new Calculator (mevents[i]); Start a task tf. StartNew (Calcs[i]. Calculation, tuple.create (i + 1, i + 3)); } Thread.Sleep (5000); Console.Write ("task is running\r\n"); for (int i = 0; i < Taskcount; i++) {//returns the index of the wait array that performed the operation, gets a specific event based on the index, and then issues a reset signal from the event int index = WaitHandle.WaitAny (waithandles); if (index = = waithandle.waittimeout) {console.write ("timeout\r\n"); } else {Mevents[index]. Reset (); Console.Write ("finished task for {0}\r\n", Calcs[index]. TaskID); }} Console.readkey (True); }} public class Calculator {//Log event status private ManualResetEventSlim mevent; public int? TaskID {get; private set;} Public Calculator (ManualResetEventSlim ev) {this.mevent = EV; public void calculation (object obj) {tuple<int, int> data = (tuple<int, int>) obj; Console.Write ("Task {0} starts calculation\r\n", Task.currentid); Thread.Sleep (New Random (). Next (3000)); TaskID = Task.currentid; Console.Write ("Task {0} is ready\r\n", Task.currentid); Mevent. Set (); } }}
After this sentence is masked, "finished task for" is often a fixed value and does not quite understand why this is the case.
I don't know if it is reset, WaitHandle will fail, WaitHandle.WaitAny (waithandles) will not get duplicate records
"C # Advanced Programming version Seventh" Multiple Threads events