Reputation: 71167
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
Upvotes: 2
Views: 805
Reputation: 71167
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...
Upvotes: 1