HI WELCOME TO SIRIS

Difference between Monitor and lock in C#

Leave a Comment
we will discuss, the Difference between Monitor class and lock.

Both Monitor class and lock provides a mechanism that synchronizes access to objects. lock is the shortcut for Monitor.Enter with try and finally.

This means that, the following code 

static object _lock = new object();
public static void AddOneMillion()
{
    for (int i = 1i <= 1000000i++)
    {
        lock (_lock)
        {
            Total++;
        }
    }
}

can be rewritten as shown below:
static object _lock = new object();
public static void AddOneMillion()
{
    for (int i = 1i <= 1000000i++)
    {
        // Acquires the exclusive lock
        Monitor.Enter(_lock);
        try
        {
            Total++;
        }
        finally
        {
            // Releases the exclusive lock
            Monitor.Exit(_lock);
        }
    }
}

In C# 4, it is implement slightly differently as shown below
static object _lock = new object();
public static void AddOneMillion()
{
    for (int i = 1i <= 1000000i++)
    {
        bool lockTaken = false;
        // Acquires the exclusive lock
        Monitor.Enter(_lockref lockTaken);
        try
        {
            Total++;
        }
        finally
        {
            // Releases the exclusive lock
            if (lockTaken)
                Monitor.Exit(_lock);
        }
    }
}

So, in short, lock is a shortcut and it's the option for the basic usage. If you need more control to implement advanced multithreading solutions using TryEnter() Wait(), Pulse(), & PulseAll() methods, then the Monitor class is your option.

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.