当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - How does Monitor.Enter work?

问题描述:

I've been doing some investigation to find exactly how Monitor.Enter works internally. I looked through the code and it seems the actual mechanism for entering is inside an external function:

[System.Security.SecuritySafeCritical]

[ResourceExposure(ResourceScope.None)]

[MethodImplAttribute(MethodImplOptions.InternalCall)]

private static extern void ReliableEnterTimeout(Object obj, int timeout, ref bool lockTaken);

Does anyone know what this function does or what the general mechanism of Monitor.Enter is? How does it know which objects are locked?

网友答案:

How does it know which objects are locked?

Every object in .NET has two extra (hidden.. you can't see them) overhead members.

  • A "type object pointer". This is just a reference to the Type instance of the object. In fact, you can "access" this by calling GetType().
  • A "sync block index". This is a native WORD size integral type which is an index into the CLR's internal array of "Sync Blocks".

The Sync Block structure contains a field that can be marked for locking. Basically, when you lock an object, this field is switched on. When the lock is released, it is switched off (basically - I haven't looked at the SSCLI for long enough to delve deeper into how that sort of operation works - I believe it is based on EnterCriticalSection though..).

The MethodImplOptions.InternalCall arguments you've passed to the attribute above means that the actual implementation of that method resides in the CLR.. which is why you can't browse any further through the code.

分享给朋友:
您可能感兴趣的文章:
随机阅读: