如何确定是否正在处理

如何确定是否正在处理

本文介绍了如何确定是否正在处理.NET异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在调查C#中的编码模式,其中我们希望使用一个特殊类的using子句,其中 Dispose()方法不同事情取决于使用的身体是否正常退出或有异常。



为了我的最大的了解,CLR跟踪当前正在处理的异常,直到它被catch处理程序消耗。然而,这些信息是否以任何方式暴露于代码访问中并不完全清楚。你知道是否是,如果是,如何访问它?



例如:

  using(var x = new MyObject())
{
x.DoSomething();
x.DoMoreThings();


class MyObject:IDisposable
{
public void Dispose()
{
if(ExceptionIsBeingHandled)
回滚);
else
Commit();
}
}

这看起来几乎像系统.Transactions.TransactionScope ,除了成功/失败不是通过调用 x.Complete()确定,而是基于使用正文正常退出。

解决方案

描述了一个黑客来检测如果您的代码在异常处理模式下执行。它使用以查看异常是否为活动。



但请记住:


We're investigating a coding pattern in C# in which we'd like to use a "using" clause with a special class, whose Dispose() method does different things depending on whether the "using" body was exited normally or with an exception.

To the best of my understanding, the CLR keeps track of the current exception being handled until it's been consumed by a "catch" handler. However it's not entirely clear whether this information is exposed in any way for the code to access. Do you know whether it is, and if so, how to access it?

For example:

using (var x = new MyObject())
{
    x.DoSomething();
    x.DoMoreThings();
}

class MyObject : IDisposable
{
    public void Dispose()
    {
        if (ExceptionIsBeingHandled)
            Rollback();
        else
            Commit();
    }
}

This looks almost like System.Transactions.TransactionScope, except that success/failure is not determined by a call to x.Complete(), but rather based on whether the using body was exited normally.

解决方案

http://www.codewrecks.com/blog/index.php/2008/07/25/detecting-if-finally-block-is-executing-for-an-manhandled-exception/ describes a "hack" to detect if your code is executed in exception handling mode or not. It uses Marshal.GetExceptionPointers to see if an exception is "active".

But keep in mind:

这篇关于如何确定是否正在处理.NET异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 10:41