Manual thread Synchronization
1> use WaitHandle to do data synchronization or data waiting based on the
AutoResetEvent () If there is no blocking then normal waitall is all without blocking can be through WaitAll is a no blocking on through
usingSystem;usingSystem.Threading; Public Sealed classApp {//Define An array with the AutoResetEvent waithandles. Staticwaithandle[] Waithandles =Newwaithandle[] {NewAutoResetEvent (false), NewAutoResetEvent (false) }; //Define a random number generator for testing. StaticRandom r =NewRandom (); Static voidMain () {//Queue up and the tasks on the different threads; //wait until all tasks is completed.DateTime dt =DateTime.Now; Console.WriteLine ("Main thread is waiting for BOTH the tasks to complete."); ThreadPool.QueueUserWorkItem (NewWaitCallback (dotask), waithandles[0]); ThreadPool.QueueUserWorkItem (NewWaitCallback (dotask), waithandles[1]); WaitHandle.WaitAll (waithandles); //The time shown below should match the longest task.Console.WriteLine ("Both Tasks is completed (Time waited={0})", (DateTime.Now-DT). TotalMilliseconds); //Queue up and the tasks on the different threads; //wait until any tasks is completed.DT =DateTime.Now; Console.WriteLine (); Console.WriteLine ("The main thread is waiting for either task to complete."); ThreadPool.QueueUserWorkItem (NewWaitCallback (dotask), waithandles[0]); ThreadPool.QueueUserWorkItem (NewWaitCallback (dotask), waithandles[1]); intindex =WaitHandle.WaitAny (waithandles); //The time shown below should match the shortest task.Console.WriteLine ("Task {0} finished first (Time Waited={1}).", Index+1, (DateTime.Now-DT). TotalMilliseconds); } Static voidDotask (Object state) {AutoResetEvent is=(AutoResetEvent) state; intTime = +* R.next (2,Ten); Console.WriteLine ("performing a task for {0} milliseconds.", time); Thread.Sleep (time); Is. Set (); }}
2> C # 4.0 barrier class
Public Static voidSpeak () { for(inti =0; I <5; i++) {Console.Write (i+""); D.signalandwait ();//wait for 3 threads to go through this method. } } /// <summary> ///when reaching 3 threads triggers an action<Barrier>The first of these is the number of threads that are required to reach/// </summary> StaticBarrier d =NewBarrier (3, D1 = {Console.WriteLine (""); }); Static voidMain (string[] args) { NewThread (Speak). Start (); NewThread (Speak). Start (); NewThread (Speak). Start (); Console.readkey (); }
Data synchronization Thread C #