究竟怎样完成锁的工作? [英] How does lock work exactly?

查看:116
本文介绍了究竟怎样完成锁的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到,对于使用它们不是线程安全的对象,我们换用这样的锁code:

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
}

所以会发生什么,当多个线程同时访问同一个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转换为以下内容:

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 <一href="http://blogs.msdn.com/b/ericlippert/archive/2009/03/06/locks-and-exceptions-do-not-mix.aspx">this改变,并且它现在产生如下:

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:

使用输入就收购监视器   对象作为参数传递。如果   另一个线程已经执行了一个输入   上的对象,但尚未执行   相应的退出,当前   线程将被阻塞,直到其他   线程释放对象。它是   合法为同一线程调用   输入不止一次没有它   堵;然而,相等数量的   退出通话前必须调用   等待在物体上的其他线程   将解除。

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天全站免登陆