本文介绍了在C#我怎么能放心地离开内带try catch块的锁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一个例外锁里面发生的事情,用try-catch块的例子。

  INT零= 0 ; 
INT J = 10;

锁(sharedResource.SyncRoot)
{

{
当J = J /为零;
}
赶上(DivideByZeroException E)
{
//异常捕获锁,但没有公布
}
}

我如何安全地抓释放此锁?


解决方案

那会不会自动释放?



从MSDN锁定装置

  System.Threading.Monitor.Enter(X); 
尝试{

}
终于{
System.Threading.Monitor.Exit(X);
}



所以,你不必理会。

Here is an example of an exception happening inside a lock, with a try-catch block.

int zero = 0;
int j = 10;

lock (sharedResource.SyncRoot)
{
    try
    {
        j = j / zero;
    }
    catch (DivideByZeroException e)
    {
        // exception caught but lock not released
    }
}

How do I safely release this lock in the catch?

解决方案

Won't it be released automatically?

From the MSDN lock means

System.Threading.Monitor.Enter(x);
try {
   ...
}
finally {
   System.Threading.Monitor.Exit(x);
}

So you don't have to bother.

这篇关于在C#我怎么能放心地离开内带try catch块的锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 22:59