Home All Groups Group Topic Archive Search About

Algorithm of lock (obj) { ...} statement in C#

Author
29 Sep 2006 3:56 AM
Hyun-jik Bae
What is the algorithm of lock(obj) { ... }?

The statement above roughly makes me guess that the lock/unlock algorithm in
CLR is inefficient because it adds a critical section for each CLR object
instance.

Am I right? Please reply. Thanks in advance.

Hyun-jik Bae

Author
29 Sep 2006 5:19 AM
Carl Daniel [VC++ MVP]
Hyun-jik Bae wrote:
> What is the algorithm of lock(obj) { ... }?
>
> The statement above roughly makes me guess that the lock/unlock
> algorithm in CLR is inefficient because it adds a critical section
> for each CLR object instance.
>
> Am I right? Please reply. Thanks in advance.

No, you're not.

The C# lock state is a shortcut for a pattern using the
System.Threading.Monitor object.

lock(this)
{
    statement(s)
}

is identical to

Monitor.Enter(this);
try
{
    statement(s)
}

finally
{
Monitor.Exit(this);
}

Under the covers, Monitor uses a pool of kernel synchronization objects and
attaches them to objects as needed.   There are only as many low-level
synchronization objects in use as there are active monitors at any given
time.

-cd

AddThis Social Bookmark Button