在非UI线程上抛出异常时,如何保留堆栈跟踪

时间:2013-02-01 19:50:51

标签: c# wpf exception

这样做很糟糕,因为它不会保留堆栈跟踪:

try { /*... some code that can throw an exception ...*/ }
catch (Exception e)
{
    throw e; // ...Use "throw;" by itself instead
}

但是,如果在非UI线程上捕获异常,我想将其重新提升回UI并处理它,以便用户得到如下消息:

try { /*... some code that can throw an exception ...*/ }
catch (Exception e)
{
    Dispatcher.Invoke((Action)(() => { throw; }));
}

但是,我不能在这里单独使用throw关键字,因为C#lexer(正确)认为 throw 语句不在 catch 中。我不得不这样做:

try { /*... some code that can throw an exception ...*/ }
catch (Exception e)
{
    Dispatcher.Invoke((Action)(() => { throw e; }));
}

并重新抛出异常,这会丢失其堆栈跟踪。

有没有(简单)方法来解决这个问题(我总是可以在异常准备好切换线程时打包堆栈跟踪,但这看起来很糟糕)?

注意:我看到this thread但它的标题只相似,而不是内容。

1 个答案:

答案 0 :(得分:4)

执行此操作的常用方法是抛出 new 异常,原始包含为InnerExceptionExceptiona special constructor for this

但是如果你真的想要这样做并且你使用.Net 4.5,you can use ExceptionDispatchInfo来捕获异常的堆栈跟踪,然后在不重置堆栈跟踪的情况下将其重新抛出到其他地方。但在大多数情况下,使用旧方法将异常包装在新方法中可能更好。