Part 94 Difference between Monitor and lock in C#

preview_player
Показать описание
Text version of the video

Healthy diet is very important both for the body and mind. If you like Aarvi Kitchen recipes, please support by sharing, subscribing and liking our YouTube channel. Hope you can help.

Slides

All C# Text Articles

All C# Slides

All Dot Net and SQL Server Tutorials

In this video 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. Meaning the following code
static object _lock = new object();
public static void AddOneMillion()
{
for (int i = 1; i [= 1000000; i++)
{
lock (_lock)
{
Total++;
}
}
}

can be rewritten as shown below.
static object _lock = new object();
public static void AddOneMillion()
{
for (int i = 1; i [= 1000000; i++)
{
// 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
static object _lock = new object();
public static void AddOneMillion()
{
for (int i = 1; i [= 1000000; i++)
{
bool lockTaken = false;
// Acquires the exclusive lock
Monitor.Enter(_lock, ref 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 Montior class is your option.
Рекомендации по теме
Комментарии
Автор

Please do expalin the usage of static object _lock=new object() and please do explain about the static and non static method version. (ie) for non static method do we need to use static object _lock=new object()

RanjithKumar-qjmn
Автор

Hi Venkat... thank you for uploading such great video tutorials.... I must say yours are the best I can find online. Request you to also add videos on Mutex, Manual/Autoreset/countdown events andTask parallel as well . I am sure we mayhave better understanding over above once we have it your way of explanation. 

Also eagerly waiting for your WPF series :)

Hope we are not asking alot :D ... Your videos are really good :)

onlinevideogallery
Автор

This video is poorly named. The example in this video is an illustration of the similarities between Monitor and lock not the differences between them. I would have expected a far more in depth discussion about running time comparisons and efficiency since lock is implemented with Monitor (See MSDN). Perhaps add an additional example of why someone might use Monitor instead of lock which abstracts away the enter/exit and try/finally for you.

wilsquared
Автор

I think at minute 3 calling Monitor.Enter() outside of try block might cause a problem though:
At first I thought problem was that total is incremented even lockTaken is false; that is not a problem since lockTaken will only be false if Monitor.Enter() has already thrown an exception.
But then the new problem is that when Monitor.Enter() throws that exception and it is not done inside a try block, this try&finally will never execute; so, Monitor will not close what it has opened.

This .Enter() overload is more complicated; it will throw an exception on failure anyway, but lock may or may not be taken. Less error prone is to use .TryEnter() instead.

jaroo
Автор

hi kudvenkat, i have question, do we need to lock the variables declared inside Parallel.ForEach()? (i am using this currently)

av
Автор

Is the lock and monitor performance the same?

nadavvalotker