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

H

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
 
C

Carl Daniel [VC++ MVP]

Hyun-jik Bae said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top