Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

c# - Background worker exception handling

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

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;

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

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"?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...