I see that for using objects which are not thread safe we wrap the code with a lock like this:
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?
The
lockstatement is translated by C# 3.0 to the following:In C# 4.0 this has changed and it is now generated as follows:
You can find more info about what
Monitor.Enterdoes here. To quote MSDN:The
Monitor.Entermethod will wait infinitely; it will not time out.