6

I have a WPF application that has a BackgroundWorker. I throw an exception in this BGW but it is not shown any where!, just the background worker fires its WorkerFinished event.

Where is it going?

mans
  • 17,104
  • 45
  • 172
  • 321
  • 1
    From the MSDN entry on `BackgroundWorker`: "If the operation raises an exception that your code does not handle, the BackgroundWorker catches the exception and passes it into the RunWorkerCompleted event handler, where it is exposed as the Error property of System.ComponentModel.RunWorkerCompletedEventArgs." – dlev May 17 '13 at 16:16
  • 1
    Nothing to do with WPF. Give http://www.albahari.com/threading/ a read, it'd be time well spent! – Yahya May 17 '13 at 16:20

2 Answers2

7

Each thread has it's own call stack; exceptions can only move up their own call stack, there's no way for them to "bleed" over into another thread's call stack.

When your exception bubbles up to the BackgroundWorker's code that fires the DoWork event handler the exception will end up being explicitly caught and stored in the Error property rather than allowing it to reach the top of the call stack and crash the application.

If you want the program to end if your BGW throws an exception then you'll need to handle the completed event, check for an exception, and then re-throw it or throw a new exception.

Servy
  • 202,030
  • 26
  • 332
  • 449
  • 1
    An exception in Background thread will also crash the application, in this case BackgroundWorker class is designed not to crash the application if exception is thrown. – skjagini May 17 '13 at 16:37
4

Look here, there's a nice example. The exception in throwned in the RunWorkercompleted

Unhandled exceptions in BackgroundWorker

var worker = new BackgroundWorker();
worker.DoWork += (sender, e) => 
    { 
        throw new InvalidOperationException("oh shiznit!"); 
    };
worker.RunWorkerCompleted += (sender, e) =>
    {
        if(e.Error != null)
        {
            MessageBox.Show("There was an error! " + e.Error.ToString());
        }
    };
worker.RunWorkerAsync();
Community
  • 1
  • 1
the_lotus
  • 12,668
  • 3
  • 36
  • 53