Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9282069
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T18:16:57+00:00 2026-06-18T18:16:57+00:00

How does one get a meaningful BackgroundWorker.Error when DoWork must call a delegate that

  • 0

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

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T18:16:59+00:00Added an answer on June 18, 2026 at 6:16 pm

    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…

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Does any one know if its possible to animate app.current.mainwindow.width so that you get
In Silverlight, how does one get row data from a DataGrid that is full
How does one get a handle to a CheckBox control that's embedded in a
How does one get gcc to not stop compiling after the first error. Is
How does one get the screen resolution of the current monitor? By current monitor,
How does one write a (Intel) F90 function that converts a string into lowercase
How does one alternate row colors in a table in django that's generated using
According to the Qt documentation, QVariant::operator== does not work as one might expect if
How does one get the caller (sender) of the kendoui datepicker widget? Or any
How does one get the upper left coordinates of a framework elements bounding rectangle?

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.