Thursday 7 January 2016

Threading with Monitor

Provides a mechanism that synchronizes access to objects.

The Monitor class controls access to objects by granting a lock for an object to a single thread. Object locks provide the ability to restrict access to a block of code, commonly called a critical section. While a thread owns the lock for an object, no other thread can acquire that lock. You can also use Monitor class to ensure that no other thread is allowed to access a section of application code being executed by the lock owner, unless the other thread is executing the code using a different locked object.

Use Monitor to lock objects other than strings (that is, reference types other than String), not value types.
Monitor has the following features:
·         It is associated with an object on demand.
·         It is unbound, which means it can be called directly from any context.
·         An instance of the Monitor class cannot be created.
The following information is maintained for each synchronized object:
·         A reference to the thread that currently holds the lock.
·         A reference to a ready queue, which contains the threads that are ready to obtain the lock.
·         A reference to a waiting queue, which contains the threads that are waiting for notification of a change in the state of the locked object.

The following table describes the actions that can be taken by threads that access synchronized objects:
Action
Description
Acquires a lock for an object. This action also marks the beginning of a critical section. No other thread can enter the critical section unless it is executing the instructions in the critical section using a different locked object.
Releases the lock on an object in order to permit other threads to lock and access the object. The calling thread waits while another thread accesses the object. Pulse signals are used to notify waiting threads about changes to an object's state.
Pulse(signal),PulseAll
Sends a signal to one or more waiting threads. The signal notifies a waiting thread that the state of the locked object has changed, and the owner of the lock is ready to release the lock. The waiting thread is placed in the object's ready queue so that it might eventually receive the lock for the object. Once the thread has the lock, it can check the new state of the object to see if the required state has been reached.
Releases the lock on an object. This action also marks the end of a critical section protected by the locked object.

Ex.
using System;
using System.IO;
using System.Threading;
namespace monitorclass
{
    class Program
    {
        static object locker = new object();
        static void ThreadMain()
        {
            Thread.Sleep(800);    // Simulate Some work
            WriteToFile();          // Access a shared resource / critical section
        }
        static void WriteToFile()
        {
            String ThreadName = Thread.CurrentThread.Name;
            Console.WriteLine("{0} using vinodsinghjnp.blogspot.com", ThreadName);
            Monitor.Enter(locker);
            try
            {
                using (StreamWriter sw = new StreamWriter(@"D:\test.txt", true))
                {
                    sw.WriteLine(ThreadName);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                Monitor.Exit(locker);
                Console.WriteLine("{0} releasing vinodsinghjnp.blogspot.com", ThreadName);
            }
        }
        static void Main(string[] args)
        {
            for (int i = 0; i < 3; i++)
            {
                Thread thread = new Thread(new ThreadStart(ThreadMain));
                thread.Name = String.Concat("Thread - ", i);
                thread.Start();

            }
            Console.Read();
        }
    }

}

No comments:

Post a Comment

Contact Us:

Email:

Vinodkumar434@gmail.com,
vinodtechnosoft@gmail.com

Skype Name:

vinodtechnosoft