Thread Synchronization using VS.NET 2005

Introduction

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.

What is 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 in Synchronization

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.

Syntax

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 in Synchronization

Similar to Enter, but will never block, or will only block for a certain amount of time.

Monitor.Exit Method in Synchronization

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.

Syntax

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 iin Synchronization

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 in Synchronization

Notifies a thread in the waiting queue of a change in the object's state.

Syntax

public static void Pulse (object obj);

Where obj represents the object to send the pulse.

Monitor.PulseAll Method in Synchronization

This method sends a notification to all waiting objects.

Syntax

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.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, Name: {1}, Hash: {2}, Hello!", 
                    iThreadID, Thread.CurrentThread.Name, iThreadID);
                Console.WriteLine();

                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 the 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 the started thread to become alive
            while (!oThread1.IsAlive) ;

            // Create the 2nd thread object, passing in the Alpha.Beta method via a ThreadStart delegate,
            // on the same oAlpha instance
            Thread oThread2 = new Thread(new ThreadStart(oAlpha.Beta));
            oThread2.Name = "Green";

            // Start the 2nd Thread
            oThread2.Start();

            // Spin waiting for the started thread to start
            while (oThread2.ThreadState == ThreadState.Unstarted) ;

            Console.ReadLine();
        }
    }
}

Output

Threads


Similar Articles