我看到为了使用非线程安全的对象,我们用这样的锁包装代码:
private static readonly Object obj = new Object();
lock (obj)
{
// thread unsafe code
}
那么,当多个线程访问同一代码时会发生什么(假设它在 ASP.NET Web 应用程序中运行)。他们在排队吗?如果是这样,他们会等多久?
使用锁对性能有何影响?
最佳答案
lock
语句由 C# 3.0 翻译为以下内容:
var temp = obj;
Monitor.Enter(temp);
try
{
// body
}
finally
{
Monitor.Exit(temp);
}
在 C# 4.0 中 this has changed现在生成如下:
bool lockWasTaken = false;
var temp = obj;
try
{
Monitor.Enter(temp, ref lockWasTaken);
// body
}
finally
{
if (lockWasTaken)
{
Monitor.Exit(temp);
}
}
您可以找到有关 Monitor.Enter
功能的更多信息 here .引用 MSDN:
Use
Enter
to acquire the Monitor on the object passed as the parameter. If another thread has executed anEnter
on the object but has not yet executed the correspondingExit
, the current thread will block until the other thread releases the object. It is legal for the same thread to invokeEnter
more than once without it blocking; however, an equal number ofExit
calls must be invoked before other threads waiting on the object will unblock.
Monitor.Enter
方法将无限等待;它不会超时。
关于c# - lock 语句在幕后做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6029804/