Mega Code Archive

 
Categories / C# Tutorial / Thread
 

Use Monitor to control more than one Threads

using System; using System.Threading; class MyClass {   private int counter;   public void DoSomeWork()   {     lock(this)     {       counter++;       // Do the work.       for(int i = 0; i < 5; i++)       {         Console.WriteLine("counter: {0}, i: {1}, current thread: {2}",           counter, i, Thread.CurrentThread.Name);         Thread.Sleep(1000);       }     }   } } public class MainClass {   public static int Main(string[] args)   {     MyClass w = new MyClass();     Thread workerThreadA = new Thread(new ThreadStart(w.DoSomeWork));     workerThreadA.Name = "A";     Thread workerThreadB = new Thread(new ThreadStart(w.DoSomeWork));     workerThreadB.Name = "B";     Thread workerThreadC = new Thread(new ThreadStart(w.DoSomeWork));     workerThreadC.Name = "C";     // Now start each one.     workerThreadA.Start();     workerThreadB.Start();     workerThreadC.Start();          return 0;   } } counter: 1, i: 0, current thread: A counter: 1, i: 1, current thread: A counter: 1, i: 2, current thread: A counter: 1, i: 3, current thread: A counter: 1, i: 4, current thread: A counter: 2, i: 0, current thread: B counter: 2, i: 1, current thread: B counter: 2, i: 2, current thread: B counter: 2, i: 3, current thread: B counter: 2, i: 4, current thread: B counter: 3, i: 0, current thread: C counter: 3, i: 1, current thread: C counter: 3, i: 2, current thread: C counter: 3, i: 3, current thread: C counter: 3, i: 4, current thread: C