0

I know this is a bit similar to the question Background worker exception handling but it is a bit different.

So based on my understanding of backgroundworkers when an exception occurs in the dowork() method the exception is passed to e.Error in the RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e). My question has a few parts.

1.) Will do work cease executing all other code after the line where the exception happened and then pass to RunWorkerCompleted? And is it necessary/best practice to use try/catch in DoWork() to ensure this behavior?

2.) When throwing from inside the the DoWork() or RunWorkerCompleted() methods where are the exceptions being thrown too. Example:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    try
    { 
       //Should I be putting code in this as well as getting the exception in `RunWorkerCompleted()`?
       //Or is the already how the background worker works already with out me needing to explicitly put the try/catch?  
    }
    catch (Exception ex)
    {
        throw ex; //is this throwing to the 'RunWorkerCompleted()` or outside the thread to error handling on in the thread where RunWorkerAsync() was called?
    } 
}

private void backgroundowrker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if (e.Error != null
    {
        throw e.Error; //This throws it back to the thread that called `RunWorkerAsync()` right?
    }
}
Community
  • 1
  • 1
user5999614
  • 147
  • 1
  • 10
  • 4
    Side note, change `throw ex;` to just `throw;`. With the former you lose the entire call stack, a very bad practice which unfortunately is very common. – Igor Mar 04 '16 at 16:01
  • What happens when you test it? Just throw an exception in the method `backgroundWorker1_DoWork` without catching it, what did you observe? It seems both your questions are easy to test and get answers to. – Igor Mar 04 '16 at 16:04
  • @Igor Does `throw;` still throw the exception even if it is a custom exception? – user5999614 Mar 04 '16 at 16:11
  • 1
    Yes, it basically rethrows the exception you caught in the catch block but maintains the state of the stacktrace. – Igor Mar 04 '16 at 16:20

1 Answers1

1
  1. Any code within the DoWork method after an exception is thrown will be unreachable code so it won't be run, Visual Studio will actually warn you of that. In general using exceptions as flow control is frowned upon -- instead I would use a return type that contains an error field so you can explicitly handle it but that really depends on the scenario.
  2. The RunWorkerCompleted will run on the thread that initiated the async method call. That is, whichever thread calls RunWorkerAsync will be the one that has the exception raised

I'll just caveat by saying I haven't used a background worker in years -- the newer async functionality in .NET/C# is just cleaner to use.

Ayubinator
  • 148
  • 1
  • 4