Monitors

A monitor is the most basic synchronization construct.

Any object can have a monitor associated with it, and no monitor can be associated with more than one object.

Monitors have a “lock,” which may be acquired by only one thread at a time. It must be released by that thread before another thread can acquire it.

You can guard a section of code by declaring an object that is visible to all threads, such as a class field, and having a section of code acquire the lock from that monitor before performing some operation and then release the lock when it completes.

Console Application

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace pr10
{
class Program
{
static object myLockObject = new Object();
static void SayHello()
{
Console.WriteLine("Hello, ");
Thread.Sleep(1000);
Monitor.Enter(myLockObject); // Acquire the lock.
Console.WriteLine("Wonderful "); // This section of code
Thread.Sleep(1000); // is run by only one
Console.WriteLine("World"); // thread at a time.
Monitor.Exit(myLockObject); // Release the lock.
}
static void Main(string[] args)
{
Thread thread1 = new Thread(new ThreadStart(SayHello));
Thread thread2 = new Thread(new ThreadStart(SayHello));
thread1.Start();
thread2.Start();
Console.ReadLine();
}
}
}

MSDN Info

Leave a Reply