Background worker exception handling

前端 未结 3 2066
天命终不由人
天命终不由人 2020-12-17 19:56

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 o

相关标签:
3条回答
  • 2020-12-17 20:04

    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

    0 讨论(0)
  • 2020-12-17 20:04

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

    No you can't do this because bgWorker.RunWorkerAsync(); it's a method (not an event). f you are running under the Visual Studio debugger, the debugger will break at the point in the DoWork event handler where the unhandled exception was raised. So you can do something like this

     private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
            {
                try
                {
                    //put your break point here 
                     // here you can capture your exception  
                }
                catch (Exception ex)
                {
                    // here  catch your exception and decide what to do                  
                    throw;
                }
    
    
    
            }
    
    0 讨论(0)
  • 2020-12-17 20:20

    Try this

    void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
    
            if (e.Error != null)
               throw new Exception("My Custom Error Message", e.Error);
    
    0 讨论(0)
提交回复
热议问题