Csharp/CSharp Tutorial/Thread/synchronized
<source lang="csharp">using System; using System.Collections.Generic; using System.Text; using System.Threading;
class Tester{ static int counter = 0; static void Main() { Thread t1 = new Thread( new ThreadStart( Incrementer ) ); t1.IsBackground = true; t1.Name = "ThreadOne"; t1.Start(); Console.WriteLine( "Started thread {0}",t1.Name ); Thread t2 = new Thread( new ThreadStart( Incrementer ) ); t2.IsBackground = true; t2.Name = "ThreadTwo"; t2.Start(); Console.WriteLine( "Started thread {0}",t2.Name ); t1.Join(); t2.Join(); } public static void Incrementer(){ try{ while ( counter < 1000 ) { int temp = counter; temp++; Thread.Sleep( 1 ); counter = temp; Console.WriteLine("Thread {0}. Incrementer: {1}",Thread.CurrentThread.Name,counter ); } }catch ( ThreadInterruptedException ){ Console.WriteLine("Thread {0} interrupted! Cleaning up...",Thread.CurrentThread.Name ); } finally { Console.WriteLine("Thread {0} Exiting. ",Thread.CurrentThread.Name ); } } }</source>
Sync Delegate
<source lang="csharp">using System.Threading; using System;
public delegate int BinaryOp(int x, int y); class Program { static void Main(string[] args) { Console.WriteLine("Main() invoked on thread {0}.",Thread.CurrentThread.ManagedThreadId); BinaryOp b = new BinaryOp(Add); int answer = b(10, 10); Console.WriteLine("Doing more work in Main()!"); Console.WriteLine("10 + 10 is {0}.", answer); Console.ReadLine(); } static int Add(int x, int y) { Console.WriteLine("Add() invoked on thread {0}.",Thread.CurrentThread.ManagedThreadId); Thread.Sleep(5000); return x + y; } }</source>
Using synchronized methods
<source lang="csharp">using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime; using System.Runtime.rupilerServices; using System.Security; using System.Text; using System.Threading; public class MainClass {
private static int count = 0; private static object myMutex = new object(); [MethodImpl(MethodImplOptions.Synchronized)] public static void Main() { count++; }
}</source>