后台工作异常处理 [英] Background worker exception handling

查看:194
本文介绍了后台工作异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是如何处理的异常略有困惑。

I am slightly confused on how to deal with an exception.

我有一个运行一些长期运行的进程后台工作线程。我的理解是,如果后台工作线程的代码仍然将在RunWorkerCompleted方法最终在发生异常。

I have a background worker thread that runs some long running process. My understanding is if an exception occurs on the background worker thread the code will still end up at the RunWorkerCompleted method.

void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {

        if (e.Error != null)
           throw e.Error;

如果是这种情况是存在的把一个try catch块围绕bgWorker.RunWorkerAsync任意点( ); ?打电话,我以为不是。

If this is the case is there any point in putting a try catch block around the bgWorker.RunWorkerAsync(); call, I assume not?

我要重新抛出被夹在RunWorkerCompleted方法外,我怎么能做到这一点,而不会丢失的堆栈跟踪 - 是我上面是否正确?重新抛出异常,你应该只使用扔的时候,我读了你吗?

I want to rethrow the exception that is caught in the RunWorkerCompleted method, how can I do this without losing the stack trace - is what I have above correct? I read that you when rethrowing an exception you should just use "throw"?

推荐答案

我建议你创建一些业务特定的异常,它描述了你在后台做操作。而抛出此异常与原来的异常的内部异常:

I suggest you to create some business specific exception, which describes operation which you were doing in background. And throw this exception with original exception as inner exception:

private void bgWorker_RunWorkerCompleted(
    object sender, RunWorkerCompletedEventArgs e)
{
    if (e.Error != null)
        throw new BusinessSpecificException("Operation failed", e.Error);
    // ...
}



因此,原来的异常,其堆栈跟踪。将可用,你就会有更多的描述抛出异常。

Thus original exception with its stack trace will be available, and you'll have more descriptive exception thrown.

请注意 - 如果你不希望创建新的异常类,可以使用现有的 ApplicationException的或的Exception 。但它不是信息,如果你要抓住它的地方,那么你就无法赶上这个特殊的例外只有

Note - if you don't want to create new exception class, you can use existing ApplicationException or Exception. But its not that informative and if you are going to catch it somewhere, then you'll not be able to catch this particular exception only

这篇关于后台工作异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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