OK so I have been doing some digging and think I might finally be getting somewhere towards an informed answer to how SyncLock/Monitor.Enter works

As I mentioned in the last post, classes like Mutex and Semaphore are just wrappers around existing objects in the Windows OS, but a Monitor (and therefore the SyncLock function) does not exist in the Windows OS and is a pure .NET feature. I say 'pure' but the implementation of the Monitor's methods is actually written in unmanaged C++ code.

Anyway, basically any object that is constructed in .NET has a header in memory which contains a few fields and one of these fields is a SyncBlockIndex (thats SyncBlock not SyncLock). It looks like the .NET runtime keeps a load of these SyncBlock items in memory and basically each time you use SyncLock/Monitor.Enter on an object, the CLR associates one of these 'spare' SyncBlocks with the object you passed to SyncLock/Monitor.Enter. It does this by entering the SyncBlock's ID into the object's SyncBlockIndex field. Then when your code calls End SyncLock or Monitor.Exit then the locking object's SyncBlockIndex field is set back to a negative number to indicate that it has no SyncBlock associated with it.

So if another thread comes along and calls SyncLock/Monitor.Enter on this same object then it will see that the SyncBlockIndex field of the object is set and it will look at the SyncBlock that this field points to - if it sees that this SyncBlock is owned by another thread then it will suspend this thread and wait for the other thread to release the SyncBlock so that it can then take ownership.

So in short, I dont THINK using SyncLock incurs any kind of looping or intensive CPU usage, although I did read somewhere that it will check the SyncBlock ownership again a few times quickly before resorting to suspending the thread - presumably because sometimes the SyncBlock will have been released a few miliseconds later so it would be less efficient to suspend the thread and wait for the notification than it would be to just try again a few times first.


Well, I found it interesting even if no one else did

Oh and if anyone has anything to add to that or correct, please do!

Chris