Alex Rivera | Logout

How does System.Threading.Monitor.Enter() work?

Asked 2011-07-21T02:57:39.227
12

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.

Edit
Report

1 Answer

3

Microsoft .NET - whenever possible - tries a spinlock on the thin lock structure in the object header. (Notice how one can "lock" on any object.)

Only if there is a need for it will an event handle be used from the pool or a new one allocated.

answered 2011-07-21T21:33:34.667

Your Answer