I got a question how Monitor.Enter works. I investigated .net framework source code, and it shows this only:
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void ReliableEnter(Object obj, ref bool lockTaken);
I guess Monitor.Enter implementation is platform dependent, so I browsed Mono source code and I gave up :(
Yes, a critical section assigned for each System.Object instance may solve, but, I don't think the actual Monitor.Lock is written like this, because creating a critical section for each System.Object will cost unlimitedly. (Win32 does not allow billions of critical section objects in a process!)
Does anybody know how Monitor.Enter works? Please reply. Thanks in advance.
Looking at the Mono source code, it seems that they create a Semaphore (using CreateSemaphore
or a similar platform-specific function) when the object is first locked, and store it in the object. There also appears to be some object pooling going on with the semaphores and their associated MonoThreadsSync structures.
The relevant function is static inline gint32 mono_monitor_try_enter_internal (MonoObject *obj, guint32 ms, gboolean allow_interruption)
in the file mono/metadata/monitor.c
, in case you're interested.
I expect that Microsoft .Net does something similar.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With