The following code:
lock (_syncRoot) { // Do stuff }
Translated by the compiler to:
Monitor.Enter(_syncRoot) try { // Do stuff } finally { Monitor.Exit(_syncRoot); }
This is a naive (and old) implementation, in fact, with .NET 4.0 the implementation is more or less like this (see Eric's blog for a full link):
bool locked = false; try { Monitor.Enter(_syncRoot, ref locked); } finally { if (locked) Monitor.Exit(_syncRoot); }
EDITED
Monitor.Enter()
this say how Monitor.Enter()
works? Well, the default Mono implementation uses a semaphore to get the lock, but the Microsoft.NET implementation is different.
I was reading concurrent programming on Windows (Joe Duffy), when the paragraph caught my attention, my first answer said: "No, it does not use rotation because performance can be inefficient in general cases." The correct answer is yes, .NET Monitor
uses rotation. Both .NET Monitor
and critical Windows partitions rotate briefly before returning to the true expectation of a kernel object. This algorithm is called the “two-phase blocking protocol”, and this is necessary because context switches and kernel transitions are very expansive, with a multiprocessor machine rotation can avoid both of them.
Also, do not forget that these are implementation details and can be changed in any version (or the algorithm may differ for different hardware due to the JIT compiler).
source share