对于下面的示例,锁定是否会在执行i ++之前释放?换句话说,当在锁内调用函数时会释放锁吗?
lock (lockerobject /*which is static*/)
{
call2anotherFunction();
i++;
}
Run Code Online (Sandbox Code Playgroud)
在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它内部发生了.