Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception not caught when using BackgroundWorker

Tags:

c#

.net

exception

I have a WPF window with a BackgroundWorker. I get an exception in Send() method here:

private void worker_DoWork(object sender, DoWorkEventArgs e)
{
     smtpClient.Send(mail);
}

which in turn is invoked in a Click Event for some button like this:

private async void SendClickAsync(object sender, RoutedEventArgs e)
{
    using (MessageServiceClient client = new MessageServiceClient())
    {
        try
        {
            [...]
            worker.RunWorkerAsync();

        }
        catch (Exception ex)
        {
            MessageBox.Show("Error! Check your sender data!", "!", MessageBoxButton.OK, MessageBoxImage.Error);
            [...]
        }
    }
}

Why does this exception doesn't get handled? When I was doing it not asynchronously (everything was in SendClickAsync() method) the message box popped up nicely.

like image 295
pmichna Avatar asked Dec 17 '25 07:12

pmichna


2 Answers

When you call worker.RunWorkerAsync() method, your main thread continue execution and exits try..catch block. To handle exception use RunWorkerCompleted event handler. RunWorkerCompletedEventArgs arguement has property Error which will contain exception object:

void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if (e.Error != null)
    {
       MessageBox.Show("Error", "!", MessageBoxButton.OK, MessageBoxImage.Error);
       return;
    }
}
like image 141
Sergey Berezovskiy Avatar answered Dec 19 '25 20:12

Sergey Berezovskiy


The BackgroundWorker is using thread pool threads, so it doesn't want your code to be able to do something weird on the worker thread. That's why the BackgroundWorker swallows your exception that happened during DoWork and lets you know that it happened through RunWorkerCompletedEventArgs.Error.

like image 20
Vlad Avatar answered Dec 19 '25 19:12

Vlad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!