Mega Code Archive

 
Categories / C# Tutorial / Thread
 

Increment Monitor

using System; using System.Threading; public class MainClass {   private static Object locker = new Object();   private static int count = 0;   public int IncrementCount()   {     int rc;     lock( locker )     {       rc = ++count;     }     return rc;   }   public void DoCount()   {     for( int i = 0; i < 10; i++ )     {       System.Console.WriteLine( "Thread {0}: count = {1}", Thread.CurrentThread.Name, IncrementCount() );       Thread.Sleep( 0 );     }   }   [STAThread]   static void Main(string[] args)   {     int limit = 10;     Thread[] t = new Thread[ limit ];     for(int k = 0; k < limit; k++ )     {       MainClass b = new MainClass();       t[ k ] = new Thread( new ThreadStart( b.DoCount ) );       t[ k ].Name = "Thread " + k;     }     for(int k = 0; k < limit; k++ )     {       t[ k ].Start();     }     for(int k = 0; k < limit; k++ )     {       t[ k ].Join();     }     System.Console.WriteLine( "All threads complete" );   } }