锁内的c#函数(obj)

Ads*_*Ads 4 c#

对于下面的示例,锁定是否会在执行i ++之前释放?换句话说,当在锁内调用函数时会释放锁吗?

lock (lockerobject /*which is static*/)
{
   call2anotherFunction();
   i++;
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*ers 6

lock块退出之前,锁定不会被释放.lock不知道或不关心你在块内执行什么代码.

事实上,作为一般规则,块内部发生的事情并不为外部所知:

if (condition)
{
    // The if doesn't know what happens in here
}
Run Code Online (Sandbox Code Playgroud)

要么

using (var reader = XmlReader.Create(url))
{
    // using doesn't care what happens in here
    throw new Exception("Unless...");
} // Dispose will be called on reader here
Run Code Online (Sandbox Code Playgroud)

但只会调用Dispose,因为块已退出,而不仅仅是因为throw它内部发生了.


Fra*_*nov 6

不,仅当代码执行离开lock块的范围时才会释放锁.