【问题标题】:C# Monitor.Exit in Try/CatchC# Monitor.Exit 在 Try/Catch 中
【发布时间】:2017-06-29 14:22:17
【问题描述】:

我正在对旧源代码进行故障排除,并遇到这样的声明:

if (Monitor.TryEnter(lockObj))
{
    try
    {
        //does something
        if (failing_condition)
        {
            Monitor.Exit(lockObj);
            throw new Exception("Oops!");
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            Monitor.Exit(lockObj);
        }
    }
}

代码因System.Threading.SynchronizationLockException: Object synchronization method was called from an unsynchronized block of code. 而崩溃

是否有一种安全的方法可以在失败情况和正常执行完成时调用Monitor.Exit()

【问题讨论】:

    标签: c# multithreading try-catch


    【解决方案1】:

    只需在 finally 块中执行它,即使上面抛出异常,它也会始终运行。也不需要 catch 部分。

     if(Monitor.TryEnter(lockObj)) {
      try {
        //does something
        if(failing_condition) {      
          throw new Exception("Oops!");
        }
      }
      finally {
        Monitor.Exit(lockObj);
      }
    }
    

    【讨论】:

    • catch 块在这种情况下会覆盖异常详细信息,可以在此处使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-15
    • 1970-01-01
    • 2011-03-22
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多