110

When is it appropriate to use either the Monitor class or the lock keyword for thread safety in C#?

EDIT: It seems from the answers so far that lock is short hand for a series of calls to the Monitor class. What exactly is the lock call short-hand for? Or more explicitly,

class LockVsMonitor
{
    private readonly object LockObject = new object();
    public void DoThreadSafeSomethingWithLock(Action action)
    {
        lock (LockObject)
        {
            action.Invoke();
        }
    }
    public void DoThreadSafeSomethingWithMonitor(Action action)
    {
        // What goes here ?
    }
}

Update

Thank you all for your help : I have posted a another question as a follow up to some of the information you all provided. Since you seem to be well versed in this area, I have posted the link: What is wrong with this solution to locking and managing locked exceptions?

Community
  • 1
  • 1
smartcaveman
  • 41,281
  • 29
  • 127
  • 212

9 Answers9

98

Eric Lippert talks about this in his blog: Locks and exceptions do not mix

The equivalent code differs between C# 4.0 and earlier versions.


In C# 4.0 it is:

bool lockWasTaken = false;
var temp = obj;
try
{
    Monitor.Enter(temp, ref lockWasTaken);
    { body }
}
finally
{
    if (lockWasTaken) Monitor.Exit(temp);
}

It relies on Monitor.Enter atomically setting the flag when the lock is taken.


And earlier it was:

var temp = obj;
Monitor.Enter(temp);
try
{
   body
}
finally
{
    Monitor.Exit(temp);
}

This relies on no exception being thrown between Monitor.Enter and the try. I think in debug code this condition was violated because the compiler inserted a NOP between them and thus made thread abortion between those possible.

Aquila Sands
  • 1,471
  • 1
  • 20
  • 28
CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
  • As I stated the first example is C#4 and the other is what earlier versions use. – CodesInChaos Feb 12 '11 at 15:51
  • As a side note, C# via CLR mentions a caveat of the lock keyword: you may often want to do something to restore the corrupt state (if applicable) before releasing the lock. Since the lock keyword does not let us put things in the catch block, we should consider writing the long version try-catch-finally for non trivial routines. – kizzx2 Feb 12 '11 at 16:27
  • 5
    IMO restoring the shared state is orthogonal to locking/multi-threading. So it should be done with a try-catch/finally inside the `lock` block. – CodesInChaos Feb 12 '11 at 16:30
  • @kizzx2: I wish .net would make it easier to implement what I would consider the proper locking pattern, which would be to have unexpected exceptions that exit a lock neither release the lock, nor leave it held, but instead *invalidate* it, such that any pending or future attempts to enter would throw immediate exceptions. That way, code which critically needs the locked resource would fail fast rather than wait indefinitely, and code which would benefit from the resource but doesn't really need it would get on with its work. – supercat Jun 03 '13 at 16:44
  • 2
    @kizzx2: Such a pattern would be especially nice with reader-writer locks. If an exception occurs within code that holds a reader lock, there's no reason to expect that the guarded resource might be damaged, and thus no reason to invalidate it. If an exception occurs within a writer lock and the exception-handling code does not expressly indicate that the guarded object's state has been repaired, that would suggest that the object may be damaged and should be invalidated. IMHO, unexpected exceptions shouldn't crash a program, but should invalidate anything that may be corrupt. – supercat Jun 03 '13 at 16:48
  • Ok. Monitor enter/exit I seem to understand. But than there is a Pulse function, and it seems to be there ta wake some thread. Can anyone explain to me if it's neccessary? – Arsen Zahray Mar 09 '14 at 00:00
  • 2
    @ArsenZahray You don't need `Pulse` for simple locking. It's important in some advanced multi-threading scenarios. I have never used `Pulse` directly. – CodesInChaos Mar 10 '14 at 09:11
53

lock is just shortcut for Monitor.Enter with try + finally and Monitor.Exit. Use lock statement whenever it is enough - if you need something like TryEnter, you will have to use Monitor.

Himansz
  • 193
  • 2
  • 14
Lukáš Novotný
  • 9,012
  • 3
  • 38
  • 46
26

A lock statement is equivalent to:

Monitor.Enter(object);
try
{
   // Your code here...
}
finally
{
   Monitor.Exit(object);
}

However, keep in mind that Monitor can also Wait() and Pulse(), which are often useful in complex multithreading situations.

Update

However in C# 4 its implemented differently:

bool lockWasTaken = false;
var temp = obj;
try 
{
     Monitor.Enter(temp, ref lockWasTaken); 
     //your code
}
finally 
{ 
     if (lockWasTaken) 
             Monitor.Exit(temp); 
} 

Thanx to CodeInChaos for comments and links

Shekhar_Pro
  • 18,056
  • 9
  • 55
  • 79
  • In C#4 the lock statement is implemented differently. http://blogs.msdn.com/b/ericlippert/archive/2009/03/06/locks-and-exceptions-do-not-mix.aspx – CodesInChaos Feb 12 '11 at 15:43
22

Monitor is more flexible. My favorite use case of using monitor is:

When you don't want to wait for your turn and just skip:

//already executing? forget it, lets move on
if (Monitor.TryEnter(_lockObject))
{
    try
    {
        //do stuff;
    }
    finally
    {
        Monitor.Exit(_lockObject);
    }
}
Alex from Jitbit
  • 53,710
  • 19
  • 160
  • 149
7

As others have said, lock is "equivalent" to

Monitor.Enter(object);
try
{
   // Your code here...
}
finally
{
   Monitor.Exit(object);
}

But just out of curiosity, lock will preserve the first reference you pass to it and will not throw if you change it. I know it's not recommended to change the locked object and you don't want to do it.

But again, for the science, this works fine:

var lockObject = "";
var tasks = new List<Task>();
for (var i = 0; i < 10; i++)
    tasks.Add(Task.Run(() =>
    {
        Thread.Sleep(250);
        lock (lockObject)
        {
            lockObject += "x";
        }
    }));
Task.WaitAll(tasks.ToArray());

...And this does not:

var lockObject = "";
var tasks = new List<Task>();
for (var i = 0; i < 10; i++)
    tasks.Add(Task.Run(() =>
    {
        Thread.Sleep(250);
        Monitor.Enter(lockObject);
        try
        {
            lockObject += "x";
        }
        finally
        {
            Monitor.Exit(lockObject);
        }
    }));
Task.WaitAll(tasks.ToArray());

Error:

An exception of type 'System.Threading.SynchronizationLockException' occurred in 70783sTUDIES.exe but was not handled in user code

Additional information: Object synchronization method was called from an unsynchronized block of code.

This is because Monitor.Exit(lockObject); will act on lockObject which has changed because strings are immutable, then you're calling it from an unsynchronized block of code.. but anyway. This is just a fun fact.

Andre Pena
  • 56,650
  • 48
  • 196
  • 243
  • "This is because Monitor.Exit(lockObject); will act on lockObject". Then lock does nothing with the object? How does lock works? – Yugo Amaryl Apr 27 '19 at 06:53
  • @YugoAmaryl , I suppose it's because lock statement keeps in mind first passed reference and then use it instead of using changed reference, like: `object temp = lockObject; Monitor.Enter(temp); <...locked code...> Monitor.Exit(temp);` – Zhuravlev A. Jul 31 '19 at 12:25
3

Both are the same thing. lock is c sharp keyword and use Monitor class.

http://msdn.microsoft.com/en-us/library/ms173179(v=vs.80).aspx

RobertoBr
  • 1,781
  • 12
  • 22
  • 3
    Look at http://msdn.microsoft.com/en-us/library/ms173179(v=vs.80).aspx "In fact, the lock keyword is implemented with the Monitor class. For example" – RobertoBr Feb 12 '11 at 15:43
  • 1
    the underlying implementation of lock uses Monitor but they are not the same thing , consider the methods supplied by monitor which do not exist for lock , and the way you can lock and unlock in separate blocks of code . – eran otzap Jun 03 '13 at 17:07
3

The lock and the basic behavior of the monitor (enter + exit) is more or less the same, but the monitor has more options that allows you more synchronization possibilities.

The lock is a shortcut, and it's the option for the basic usage.

If you need more control, the monitor is the better option. You can use the Wait, TryEnter and the Pulse, for advanced usages (like barriers, semaphores and so on).

Borja
  • 2,188
  • 1
  • 18
  • 21
2

Lock Lock keyword ensures that one thread is executing a piece of code at one time.

lock(lockObject)

        {
        //   Body
        }

The lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a statement and then releasing the lock

If another thread tries to enter a locked code, it will wait, block, until the object is released.

Monitor The Monitor is a static class and belongs to the System.Threading namespace.

It provides exclusive lock on the object so that only one thread can enter into the critical section at any given point of time.

Difference between Monitor and lock in C#

The lock is the shortcut for Monitor.Enter with try and finally. Lock handles try and finally block internally Lock = Monitor + try finally.

If you want more control to implement advanced multithreading solutions using TryEnter() Wait(), Pulse(), and PulseAll() methods, then the Monitor class is your option.

C# Monitor.wait(): A thread wait for other threads to notify.

Monitor.pulse(): A thread notify to another thread.

Monitor.pulseAll(): A thread notifies all other threads within a process

SomeDutchGuy
  • 2,249
  • 4
  • 16
  • 42
Aatrey
  • 21
  • 1
0

In addition to all above explanations, lock is a C# statement whereas Monitor is a class of .NET located in System.Threading namespace.

gyousefi
  • 306
  • 3
  • 9