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 6333931
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T18:33:40+00:00 2026-05-24T18:33:40+00:00

I have a fairly complex program so I won’t dump the whole thing in

  • 0

I have a fairly complex program so I won’t dump the whole thing in here. Here’s a simplified version:

class Report {
    private BackgroundWorker worker;

    public Report(BackgroundWorker bgWorker, /* other variables, etc */) {
        // other initializations, etc
        worker = bgWorker;
    }

    private void SomeCalculations() {
        // In this function, I'm doing things which may cause fatal errors.
        // Example: I'm connecting to a database.  If the connection fails, 
        // I need to quit and have my background worker report the error
    }
}


// In the GUI WinForm app:
// using statements, etc.
using Report;

namespace ReportingService {
    public partial class ReportingService : Form {

        // My background worker
        BackgroundWorker theWorker = new BackgroundWorker() {
            WorkerReportsProgress = true
        };

        // The progress changed event
        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e) {
            // e.UserState and e.ProgressPercentage on some labels, etc.
        }

        // The do work event for the worker, runs the number crunching algorithms in SomeCalculations();
        void worker_DoWork(object sender, DoWorkEventArgs e) {
            Report aReport = e.Argument as Report;

            aReport.SomeCalculations();
        }

        // The completed event, where all my trouble is.  I don't know how to retrieve the error,
        // or where it originates from.
        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
            // How, exactly, do I get this error message? Who provides it? How?
            if (e.Error != null) {
                MessageBox.Show("Error: " + (e.Error as Exception).ToString());
            }
            else if (e.Cancelled) {
                MessageBox.Show("Canceled");
            }
            // operation succeeded
            else {
                MessageBox.Show("Success");
            }
        }

        // Initialization of the forml, etc
        public ReportingService() {
            InitializeComponent();

            theWorker.ProgressChanged += worker_ProgressChanged;
            theWorker.DoWork += worker_DoWork;
            theWorker.RunWorkerCompleted += worker_RunWorkerCompleted;
        }

        // A button that the user clicks to execute the number crunching algorithm
        private void sumButton_Click(object sender, EventArgs e) {
            Report myReport = new Report(theWorker, /* some other variables, etc */)
            theWorker.RunWorkerAsync(myReport);
        }
    }
}

Here’s my logic, and please correct me if I’m going about this the wrong way:

  1. I abstracted the class out of the GUI because it’s ~2000 lines and needs to be it’s own self contained object.

  2. I pass the background worker into my class so that I can report back the progress of my number crunching.

What I don’t know how to do is let the background worker know that an error has happened inside my class. In order to get the RunWorkerCompleted argument as an exception, where does my try/catch block need to go, and what should I do in the catch block?

Thanks for your help!

EDIT:

I’ve tried the following things to test the error handling:

Keep in mind I corrupted my database connection string to purposefully receive an error message.

In my class I do:

// My number crunching algorithm contained within my class calls a function which does this:

// try {
    using (SqlConnection c = GetConnection()) {  // note: I've corrupted the connection string on purpose
        c.Open();  // I get the exception thrown here
        using (SqlCommand queryCommand = new SqlCommand(query, c)) { /* Loop over query, etc. */ }
        c.Close();  
    }
// } catch (Exception e) { }

1.
From my understanding, an unhandled exception gets cast to the Error portion of the RunWorkerCompletedEventArgs? When I try this I get the following:

// In my winform application I initialize my background worker with these events:

void gapBW_DoWork(object sender, DoWorkEventArgs e) {
    Report aReport = e.Argument as Report;
    Report.Initialize();    // takes ~1 minute, throws SQL exception
    Report.GenerateData();  // takes around ~2 minutes, throws file IO exceptions
}

void gapBW_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {   
    if (e.Error != null) {  // I can't get this to trigger, How does this error get set?
        MessageBox.Show("Error: " + (e.Error as Exception).ToString());
    }
    else if (e.Cancelled) {
        MessageBox.Show("Canceled: " + (e.Result).ToString());
    }
    else {
        MessageBox.Show("Success");
    }
}

Visual studio says that my application chokes on c.Open() failing with an unhandled exception.

2.
When I put a try/catch block in my DoWork function:

void gapBW_DoWork(object sender, DoWorkEventArgs e) {
    try {
        Report aReport = e.Argument as Report;
        aReport.Initialize();   // throws SQL exceptions
        aReport.GenerateData(); // throws IO file exceptions
    }
    catch (Exception except) {
        e.Cancel = true;    
        e.Result = except.Message.ToString();
    }
}

void gapBW_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {   
    if (e.Error != null) {  // I can't get this to trigger, How does this error get set?
        MessageBox.Show("Error: " + (e.Error as Exception).ToString());
    }
    else if (e.Cancelled) {
        MessageBox.Show("Canceled: " + (e.Result).ToString());
    }
    else {
        MessageBox.Show("Success");
    }
}

I get a TargetInvocationException was unhandled in Program.cs at the automatically generated Application.Run(new ReportingService()); line. I placed a breakpoint on my RunWorkerCompleted and can see that e.Cancelled = true, e.Error = null, and e.UserState = null. The message contained within e.Cancelled is simply “Operation has been cancelled”. I imagine I’m receiving the TargetInvocationException from an invalid cast of e.Result (since it’s null). What I want to know though, is how come e.Error is still null and e.Canceled doesn’t contain any helpful information about why the operation was canceled?

3.
When I tried setting e.Canceled = true; from within DoWork on an exception catch, I managed to trigger the else if (e.Cancelled) { line in my RunWorkerCompleted function. I thought this was reserved for the user requesting the job being canceled though? Am I fundamentally misunderstanding how the background worker functions?

  • 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-05-24T18:33:41+00:00Added an answer on May 24, 2026 at 6:33 pm

    I tried this little test program and it works as expected:

    static void Main(string[] args)
    {
        var worker = new BackgroundWorker();
    
        worker.DoWork += (sender, e) => { throw new ArgumentException(); };
        worker.RunWorkerCompleted += (sender, e) => Console.WriteLine(e.Error.Message);
        worker.RunWorkerAsync();
    
        Console.ReadKey();
    }
    

    But when i run this programm within the debugger i also got the message about an unhandled exception at the throw-statement. But i simply pressed F5 again and it continued without any problems.

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

Sidebar

Related Questions

I am writing a fairly large and complex data analysis program and I have
I have a fairly complex CLR stored procedure. What is the best way to
I have a fairly complex set of rewrite rules to give my site pages
I have a fairly complex html form enhanced via jquery. It has multiple tabs,
I have a fairly complex (or ugly depending on how you look at it)
So I have a fairly complex activity the parent being a linearlayout with a
In my ASP.NET MVC app, I have a fairly complex edit page which combines
Our users have created MS-Excel spreadsheets which over time have evolved into fairly complex
I have a fat GUI that it getting fairly complex, and I would like
I have a web page that I use to update a fairly complex data

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.