c# - lock 语句在幕后做了什么?

标签 c# .net synchronization locking thread-safety

我看到为了使用非线程安全的对象,我们用这样的锁包装代码:

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 an Enter on the object but has not yet executed the corresponding Exit, the current thread will block until the other thread releases the object. It is legal for the same thread to invoke Enter more than once without it blocking; however, an equal number of Exit calls must be invoked before other threads waiting on the object will unblock.

Monitor.Enter 方法将无限等待;它不会超时。

关于c# - lock 语句在幕后做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6029804/

相关文章:

c# - 如何在 C# 中使用动态名称在 Microsoft Access 中创建表?

c# - 单元测试扩展方法,尝试一下,这是正确的,还是绕着房子走?

.NET 通讯应用程序

c# - 无法将 c# .Net Core 3.0 与 directx 9.0 依赖项链接起来

java - 为什么在使用同步时使用信号量?

不同 Azure 帐户中托管的数据库之间的 Azure DB 同步或镜像

c# - 如何在 Windows.Forms.PictureBox 中正确显示 Kinect 视频流?

c# - 从 DataGridTemplateColumn ContentPresenter 中删除 ErrorTemplate

c# - Directory.CreateDirectory 因无效字符而失败

c# - 字典中的 “An item with the same key has already been added”