是否有可能确定代码当前是否由于抛出异常而在 finally
处理程序的上下文中执行?我更喜欢使用 IDisposable
模式来实现进入/退出范围功能,但对这种模式的一个担忧是,如果出现异常,您可能不一定希望发生范围结束行为出现在 using
的正文中。我会寻找这样的东西:
public static class MyClass
{
public static void MyMethod()
{
using (var scope = MyScopedBehavior.Begin())
{
//Do stuff with scope here
}
}
}
public sealed class MyScopedBehavior : IDisposable
{
private MyScopedBehavior()
{
//Start of scope behavior
}
public void Dispose()
{
//I only want to execute the following if we're not unwinding
//through finally due to an exception:
//...End of scope behavior
}
public static MyScopedBehavior Begin()
{
return new MyScopedBehavior();
}
}
我还有其他方法可以完成此操作(将委托(delegate)传递给围绕具有特定行为的调用的函数),但我很好奇是否可以使用 IDisposable
模式来完成此操作。
实际上,这显然在 here 之前已经被询问和回答过.有可能以一种非常骇人听闻的方式进行检测。我实际上不会使用该技术,但很有趣的是知道它是可能的。
最佳答案
我看到的实现这个的方法需要一个额外的方法:
public static void MyMethod()
{
using (var scope = MyScopedBehavior.Begin())
{
//Do stuff with scope here
scope.Complete(); // Tells the scope that it's good
}
}
通过这样做,您的作用域对象可以跟踪它是由于错误还是成功操作而被处置。这是 TransactionScope 采取的方法,例如(参见 TransactionScope.Complete )。
关于c# - 判断是否因为抛出异常而执行到 finally block 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3301507/