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.
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:
And it is a good idea to Cancel the Bgw as well, but
CancelAsync()by itself is not enough. The code inDoWork()needs to check the Cancellation flag.