patterncsharpCritical
What does a lock statement do under the hood?
Viewed 0 times
lockstatementunderthedoeshoodwhat
Problem
I see that for using objects which are not thread safe we wrap the code with a lock like this:
So, what happens when multiple threads access the same code (let's assume that it is running in a ASP.NET web application). Are they queued? If so how long will they wait?
What is the performance impact because of using locks?
private static readonly Object obj = new Object();
lock (obj)
{
// thread unsafe code
}So, what happens when multiple threads access the same code (let's assume that it is running in a ASP.NET web application). Are they queued? If so how long will they wait?
What is the performance impact because of using locks?
Solution
The
In C# 4.0 this has changed and it is now generated as follows:
You can find more info about what
Use
the object passed as the parameter. If
another thread has executed an
on the object but has not yet executed
the corresponding
thread will block until the other
thread releases the object. It is
legal for the same thread to invoke
blocking; however, an equal number of
other threads waiting on the object
will unblock.
The
lock statement is translated by C# 3.0 to the following:var temp = obj;
Monitor.Enter(temp);
try
{
// body
}
finally
{
Monitor.Exit(temp);
}In C# 4.0 this has changed and it is now generated as follows:
bool lockWasTaken = false;
var temp = obj;
try
{
Monitor.Enter(temp, ref lockWasTaken);
// body
}
finally
{
if (lockWasTaken)
{
Monitor.Exit(temp);
}
}You can find more info about what
Monitor.Enter does here. To quote MSDN:Use
Enter to acquire the Monitor onthe object passed as the parameter. If
another thread has executed an
Enteron the object but has not yet executed
the corresponding
Exit, the currentthread will block until the other
thread releases the object. It is
legal for the same thread to invoke
Enter more than once without itblocking; however, an equal number of
Exit calls must be invoked beforeother threads waiting on the object
will unblock.
The
Monitor.Enter method will wait infinitely; it will not time out.Code Snippets
var temp = obj;
Monitor.Enter(temp);
try
{
// body
}
finally
{
Monitor.Exit(temp);
}bool lockWasTaken = false;
var temp = obj;
try
{
Monitor.Enter(temp, ref lockWasTaken);
// body
}
finally
{
if (lockWasTaken)
{
Monitor.Exit(temp);
}
}Context
Stack Overflow Q#6029804, score: 546
Revisions (0)
No revisions yet.