In .NET the lock
keyword is syntactic sugar around Monitor.Enter
and Monitor.Exit
, so you could say that this code
lock(locker)
{
// Do something
}
is the same as
Monitor.Enter(locker);
try
{
// Do Something
}
finally
{
Monitor.Exit(locker);
}
However the .NET framework also includes the MemoryBarrier
class which works in a similar way
Thread.MemoryBarrier();
//Do something
Thread.MemoryBarrier();
I am confused as when I would want to use Thread.MemoryBarrier
over the lock
/Monitor
version? I am made even more confused by a Threading Tutorial which states they function tthe same.
As far as I can see the visible difference is not needing a locking object, which I guess that using Monitor
you could do something across threads where MemoryBarrier
is on a single thread.
My gut is telling me that another key difference is MemoryBarrier
is for variables only and not for methods.
Lastly this is not related to the existing question When to use ‘volatile’ or ‘Thread.MemoryBarrier()’ in threadsafe locking code? (C#), as that is focusing on the volatile
keyword which I understand its usage of.