Synchronization is achieved in C# through the use of Monitors. Monitor is a class present in System.Threading namespace. This class provides the synchronization of threading objects using locks and wait/signals.
Monitor has the following features:
- Is associated with an object on demand.
- Is unbound, i.e., can be called directly from any Context
- Can not be instantiated.
Monitor exposes their ability to take and release the sync block lock on an object on demand via Enter, TryEnter and Exit.
The Wait, Pulse and PulseAll methods are related to SyncBlocks. It is necessary to be in a synchronized region on an object before calling Wait or Pulse on that object. Wait releases the lo9ck if it is held and waits to be notified. When Wait is notified, it returns and has obtained the lock again. Pulse signals for next thread in wait queue to proceed.
Monitor.Enter Method
The Monitor.Enter method obtains the monitor lock for an object. This method will block if another thread holds the lock. It will not block if the current thread holds the lock, however the caller must ensure that the same number of Exit calls are made as there were Enter Calls.
Enter the Monitor for an object. An object is passed as a parameter. This call will block if another thread has entered the Monitor of the same object. It will not block if the current thread has previously entered the Monitor, however the caller must ensure that the same number of Exit calls are made as there were Enter calls.
The general syntax for the Enter method is given as follows:
public static void Enter (object obj);
Where
obj represents an object on which to acquire the monitor lock.
The Thread.Interrupt method can interrupt threads waiting to enter a Monitor on an object. ThreadInterruptedException will be thrown if the thread was interrupted during a waiting state.
If another thread has executed an Enter on the object but not yet the corresponding Exit the current thread will block until the other thread releases the object. It is legal for the same thread to invoke Enter more then once (and it will not block); however, an equal number of Exit calls must be invoked before other threads waiting of the object will unblock.
Monitor.TryEnter Method
Similar to Enter, but will never block, or will only block for a certain amount of time.
Monitor.Exit Method
Releases the monitor lock. If one or more threads are waiting to acquire the lock, and the current thread has executed Exit, AS many times as it has executed Enter, one of the Treads will be unblocked and allowed to proceed.
The general syntax is given as follows:
public static void Exit(object obj);
Where
obj represents an object on which to release the monitor lock.
If the current thread owns the lock, the lock count is decremented for the specified object. If the count goes to zero (Exit has been executed as many times as Enter), other threads waiting on the object can acquire the lock.
Monitor.Wait Method
Waits for notifications passed by the Common Language Runtime from the object (via the Pulse or PluseAll method). The Wait method must be invoked from within a synchronized block of code
This method acquires the monitor withhandle for the object. If this thread holds the monitor lock for the object, it releases it. On exiting from the method, if obtains the monitor lock back.
Monitor.Pulse Method
Notifies a thread in the waiting queue of a change in the object's state. The general syntax for the method is given below
public static void Pulse (object obj);
Where
obj represents the object to send the pulse.
Monitor.PulseAll Method
This method sends a notification to all waiting objects. The syntax for the above method is given below:
public static void PulseAll(object obj);
Where
obj represents the object to send the pulse
The thread that currently holds the lock on this object invokes this method in order to Pulse all of the threads I the waiting queue of a change in the object's state. Shortly after the call to PulseAll, the threads in the waiting queue are moved to the ready queue , the thread that invoked PulseAll releases the lock, and the next thread(if there is one) in the ready queue is allowed to take control of the lock.
Note that a synchronized object holds several references, including a reference to the thread that currently holds the lock, a reference to the ready queue, which contains the threads that are ready to obtain the lock, and a reference to the waiting queue, which contains the threads that are waiting for notification of a change in the object's state. The Pulse, PulseAll, and Wait methods must be invoked from within a synchronized block of code.
This sample shows two threads writing to the console, without overwriting each other.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace SynchronizedThreads
{
public class Alpha
{
// The method that will be called when the thread is started
public void Beta()
{
int iThreadID = Thread.CurrentThread.GetHashCode();
int cLoop = 10;
while ((cLoop--) > 0)
{
//Obtain the lock
Monitor.Enter(this);
Console.Write("{0} Thread, Thread.CurrentThread.Name);
Console.WriteLine("Hash: {0}, Hello!", iThreadID);
Thread.Sleep(500);
//Release the lock
Monitor.Exit(this);
}
}
}
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Thread Sync One Sample");
Alpha oAlpha = new Alpha();
//Create the 1st thread object, passing in teh Alpha.Beta
//method via a ThreadStart delegate
Thread oThread1 = new Thread(new ThreadStart(oAlpha.Beta));
oThread1.Name = "Yellow";
//Start the 1st thread
oThread1.Start();
// Spin waiting for teh started thread to become alive
while (!oThread1.IsAlive) ;
//Create teh 2nd thread object, passing in the Alpha.Beta
//method via a ThreadStart delegate,
//on teh same oAlpha instance
Thread oThread2 = new Thread(new ThreadStart(oAlpha.Beta));
oThread2.Name = "Green";
// Start the 2nd Thread
oThread2.Start();
//Spin waiting ofr the started thread to start
while (oThread2.ThreadState == ThreadState.Unstarted)
return ;
Console.ReadLine();
}
}
}
The output for the above program will be as below: