Can someone explain, in detail, why it's possible to lock
on objects of any type in C#?
I understand what lock
is for and how to use it. I know how it expands to Monitor.Enter
/Exit
. What I'm looking for an explanation of the implementation detail and design considerations.
First of all: What is happening under the hood? For example: are there extra bits in an object instance (like there is for RTTI/vtable) that make it work? Or some kind of lookup table keyed on object references? (If so, how does this interact with the GC?) Or something else? Why don't I have to create an instance of a specific type to hold whatever the lock data is?
(And, by the way, what do Enter
and Exit
map to in native code?)
And, secondly, why is .NET designed to not have a specific type for taking out locks on? (Given that you generally just make a new object()
for the purpose anyway - and most cases where you lock "any old object" are problematic.) Was this design choice forced by the implementation detail? Or was it deliberate? And, if deliberate, was it a good choice? (I realise this second part may require speculation.)