在非UI线程上引发异常时,如何保留堆栈跟踪 [英] How can I preserve the stack trace when exception is thrown on non-UI thread

查看:99
本文介绍了在非UI线程上引发异常时,如何保留堆栈跟踪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这样做是不好的形式,因为它不保留堆栈跟踪:

Doing this is bad form because it doesn't preserve a stack trace:

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

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

However, if the exception is caught on a non-UI thread, I want to do raise it back up to the UI and handle it so the user gets the message like so:

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

但是,我不能在这里单独使用throw关键字,因为C#词法分析器(正确)认为 throw 语句不在 catch 内.我必须改为:

However, I can't use the throw keyword by itself here because the C# lexer (correctly) doesn't think the throw statement is inside of a catch. I have to instead do:

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

并重新引发该异常,它将丢失其堆栈跟踪.

and re-throw the exception, which loses its stack trace.

是否有任何(简便)的方法来解决此问题(在异常准备切换线程时,我总是可以打包堆栈跟踪,但这似乎很关键)?

Is there any (easy) way to get around this (I could always package the stack trace at the time the exception is ready to switch threads, but that seems hokey)?

注意:我看到了此线程,但仅在标题上相似,而在内容上相似.

Note: I saw this thread but it's similar in title only, not content.

推荐答案

通常的方法是抛出 new 异常,原始异常包含在InnerException中. Exception具有为此的特殊构造方法.

The usual way to do this is to throw a new exception, with the original included as InnerException. Exception has a special constructor for this.

但是,如果您确实要执行此操作,并且您使用的是.Net 4.5,请

But if you really want to do this and you're on .Net 4.5, you can use ExceptionDispatchInfo to capture the stack trace of the exception and then rethrowing it somewhere else without resetting the stack trace. But in most situations, using the old method of wrapping the exception in a new one is probably better.

这篇关于在非UI线程上引发异常时,如何保留堆栈跟踪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆