user17753
user17753

Reputation: 3161

background worker throwing exceptions on abrupt program end

I have a very basic windows forms app, working in C#, and I was trying out the Background Worker. I followed the base code on that page for the most part.

    void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
            progressBar.Value = e.ProgressPercentage;
    }

Everything works great, except for if the background worker is doing work when the window is closed while it is running (e.g. hitting the X). The above method is throwing a null reference exception (I presume on the progressBar?).

I did put this on the closing method:

    private void Form_FormClosing(object sender, FormClosingEventArgs e)
    {
        if(bgWorker.WorkerSupportsCancellation == true)
            bgWorker.CancelAsync();
    }

But, this did not solve the issue. I'm wondering why this is happening, I know it's isolated to the progressBar, because if I remove that line no exceptions are thrown when I close the window while it's busy.

Upvotes: 1

Views: 184

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273264

Yes, when you close the Window then the controls including the ProgressBar are destroyed. Trying to access them from the Bgw without checking will result in an error.

You can safeguard like this:

void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
   if ((progressBar == null) || progressBar.IsDisposed)
       return;

   progressBar.Value = e.ProgressPercentage;
}

And it is a good idea to Cancel the Bgw as well, but CancelAsync() by itself is not enough. The code in DoWork() needs to check the Cancellation flag.

Upvotes: 2

Related Questions