2

How does one get a meaningful BackgroundWorker.Error when DoWork must call a delegate that might throw an exeption?

I'm implementing a static MsgBox class that exposes various ways of conveying custom messages to the user (using a custom message form).

One of the exposed methods, ShowProgress, instantiates a ProgressMessageBoxForm (derived from the custom MessageBoxForm) which displays a progress bar while some background operation is happening (letting user cancel the operation all the while). If running a background task on a modal form sounds awkward, consider a signature like this:

public static DialogResult ShowProgress(string title, string message, _
    Action<AsyncProgressArgs> progressAction)

The idea is to encapsulate a background worker that delegates its "work" to any provided method (/handler), while allowing that method to "talk" back and report progress and cancellation... and ideally error status. Whether the form is modal or not has no relevance in this context, the ability to display progress of a running task in a progress bar on a cancellable modal form that also automatically closes unless a checkbox is un-checked so as to remain visible and displaying a success status upon completion, is a required feature.

Here's the AsyncProgressArgs class in question:

public class AsyncProgressArgs
{
    private readonly Action<int, string> _update;
    private readonly BackgroundWorker _worker;
    private readonly DoWorkEventArgs _workEventArgs;

    public AsyncProgressArgs(Action<int, string> updateProgress, BackgroundWorker worker, DoWorkEventArgs e)
    {
        _update = updateProgress;
        _worker = worker;
        _workEventArgs = e;
    }

    /// <summary>
    /// Reports progress to underlying <see cref="BackgroundWorker"/>.
    /// Increments <see cref="ProgressBar"/> value by specified <see cref="int"/> amount and
    /// updates the progress <see cref="Label"/> with specified <see cref="string"/> caption.
    /// </summary>
    public Action<int, string> UpdateProgress { get { return _update; } }

    /// <summary>
    /// Verifies whether asynchronous action is pending cancellation,
    /// in which case asynchronous operation gets cancelled.
    /// </summary>
    public void CheckCancelled()
    {
        _workEventArgs.Cancel = _worker.CancellationPending;
    }
}

The BackgroundWorker's DoWork event handler then invokes the method that was passed to the custom messagebox

protected virtual void worker_DoWork(object sender, DoWorkEventArgs e)
{
    // *** If RunWorkerCompletedEventArgs.Error caught exceptions,
    //     then this try/catch block wouldn't be needed:
    // try
    // {
           _startHandler(this, new AsyncProgressArgs(UpdateProgressAsync, _worker, e));
    // }
    // catch(Exception exception)
    // {
    //     if (MsgBox.Show(exception) == DialogResult.Retry)
    //     {
    //         BeginWork(_startHandler);
    //     }
    //     else
    //     {
    //         Hide();
    //     }
    // }
}

Given a method such as this:

private void AsyncProgressAction(AsyncProgressArgs e)
{
    // do some work:
    Thread.Sleep(200);

    // increment progress bar value and change status message:
    e.UpdateProgress(10, "Operation #1 completed.");

    // see if cancellation was requested:
    e.CheckCancelled();


    // do some work:
    Thread.Sleep(500);

    // increment progress bar value and change status message:
    e.UpdateProgress(30, "Operation #2 completed.");

    // see if cancellation was requested:
    e.CheckCancelled();

    // ...

    // throw new Exception("This should be caught by the BackgroundWorker");
}

The calling code can look like this:

MsgBox.ShowProgress("Async Test", "Please wait while operation completes.", _
    AsyncProgressAction);

Everything works as expected (the progress bar moves, the process can be cancelled), until an exception gets thrown in the action method. Normally the BackgroundWorker would catch it and store it in its Error property, but here this doesn't happen.

Thus, the code in the passed action method needs to handle its own exceptions and if it doesn't, it remains unhandled and the program dies a horrible death.

The question is, is it possible to have such a construct and still somehow be able to have a meaningful Error property when the process completes? I want to be able to Throw new Exception() anywhere in the action method and have it handled in the encapsulated worker.

Side note, I resorted to BackgroundWorker because with Task I couldn't get the progress bar to move until all the work was done, and I'd like to avoid dealing with Thread object instances directly.

EDIT This is a non-issue, the compiled app does not blow up. Actually, I got confused by the debugger breaking on the exception being thrown in the delegate method. As pointed out in the comments below, execution/debugging can continue afterwards, and whatever error-handling logic is intended to run, will run. I was expecting BackgroundWorker to somehow catch the exception and the debugger to keep going, but it turns out the exception is caught and still the debugger breaks.

I should have read this before: Unhandled exceptions in BackgroundWorker

Community
  • 1
  • 1
Mathieu Guindon
  • 69,817
  • 8
  • 107
  • 235
  • I'm not sure why you're defining your own `EventHandler` and `EventArgs` to support progress updates and cancellation. The `BackgroundWorker` class provides all of the events and methods needed to do so. – JosephHirn Feb 10 '13 at 05:14
  • @Ginosaji thanks and you are right, I have switched EventHandler delegate to Action delegate and EventArgs-derived type to a standalone args class. Much cleaner like this, but the problem remains that I can't trust `BackgroundWorker` to pick up an exception that occurs in the delegate method's body, which leaves me with a worthless `RunWorkerCompletedEventArgs.Error` and the obligation to wrap the invocation with a try/catch. Rethrowing the exception in the `DoWork` handler doesn't help either. – Mathieu Guindon Feb 10 '13 at 08:10
  • I just wrote up a quick progress dialog and I can't seem to reproduce this problem. Even when the `DoWork` handler invokes a delegate that throws an exception, it is stored in `RunWorkerCompletedEventArgs.Error`. – JosephHirn Feb 10 '13 at 08:48
  • Interesting... My debugger breaks on the `throw new Exception()` line. – Mathieu Guindon Feb 10 '13 at 08:57
  • 1
    As does mine, but I just press continue and it continues to the breakpoint in `RunWorkerCompleted` where `e.Error` contains the exception details. I believe you can configure the debugger to not break on the `throw new Exception()` line. – JosephHirn Feb 10 '13 at 15:27
  • @Ginosaji Argh! You've got to be kidding me! Everything DOES work as expected, this is yet another Code-18 non-issue I've posted on SO... Indeed, execution can F5-continue on the throwing line, and I can put a break point in RunWorkerCompleted and the compiled executable behaves exactly as expected! I was scratching my head over a zealous debugger that lead me to believe the deployed app would blow up! I wish I could triple vote-up your comment, it was enlightening! Thanks again! – Mathieu Guindon Feb 10 '13 at 22:22

1 Answers1

1

I should have read this before: Unhandled exceptions in BackgroundWorker.

This is a very, very long question with lots of context for a simple non-issue: the VS debugger stops and misleadingly says "Exception was unhandled by user code" as it would for an unhandled exception... when it actually means "BackgroundWorker task has thrown an exception and the debugger is letting you know about it because otherwise you would think the BackgroundWorker is swallowing it."

The exception can be F5'd / ignored to resume execution, the exception does end up in RunWorkerCompletedEventArgs.Error as expected, and the deployed app does not blow up in the user's face.

Posting this answer to remove this question from the (overflowing?) stack of unanswered questions...

Community
  • 1
  • 1
Mathieu Guindon
  • 69,817
  • 8
  • 107
  • 235