引擎盖下的锁语句有什么作用? [英] What does a lock statement do under the hood?

查看:55
本文介绍了引擎盖下的锁语句有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到对于使用不是线程安全的对象,我们使用如下锁将代码包装起来:

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
}

因此,当多个线程访问相同的代码(假设它正在ASP.NET Web应用程序中运行)时会发生什么.他们排队了吗?如果是这样,他们将等待多长时间?

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?

推荐答案

C#3.0将 lock 语句转换为以下内容:

The lock statement is translated by C# 3.0 to the following:

var temp = obj;

Monitor.Enter(temp);

try
{
    // body
}
finally
{
    Monitor.Exit(temp);
}

在C#4.0中这已更改,现在生成如下:

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); 
    }
}

您可以找到有关 Monitor.Enter 做什么的更多信息.此处.引用MSDN:

You can find more info about what Monitor.Enter does here. To quote MSDN:

使用 Enter 在以下位置获取监视器作为参数传递的对象.如果另一个线程执行了 Enter 在对象上但尚未执行相应的 Exit ,当前线程将阻塞,直到另一个线程释放对象.它是合法调用同一线程输入多次(不输入)阻塞但是,相等数量的必须先调用 Exit 调用等待对象的其他线程将解除封锁.

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 方法将无限期等待;它会超时.

The Monitor.Enter method will wait infinitely; it will not time out.

这篇关于引擎盖下的锁语句有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆