Safely close form while backgroundworkers are running

Xancholy

Well-known member
Joined
Aug 29, 2006
Messages
143
Programming Experience
Beginner
When I open my form, I fire a number of backgroundworkers to load form data.

If a user tries to close the form too soon while workers are running, it throws an exception (obviously)

My question is : what is the best practice to safely cancel running async operations when a form is closed.

I'd appreciate if someone could point me to some sample code. Thanks.
 
If a user tries to close the form too soon while workers are running, it throws an exception (obviously)
Perhaps, but user doesn't see this, BackgroundWorker catches all exceptions that may occur and pass them to the RunWorkerCompleted event through e.Error. While debugging you will get the VS exception dialog if you have break option for user-unhandled exceptions (default), which you also may choose to continue from.
My question is : what is the best practice to safely cancel running async operations when a form is closed.
To safely cancel Bgw call its CancelAsync method, look out in DoWork for CancellationPending and stop working if requested. Obviously this is only possible for loops or between multiple sequential calls. In FormClosing event you can check if Bgw IsBusy, if so you CancelAsync and can loop Application.DoEvents() until Bgw is not busy any longer.

BackgroundWorker also runs as background thread which is terminated when form is closed, so the unsafe method is to do nothing and let it rip, this is the same method as doing a Thread.Abort, may be valid if you know there is no problem with such abruption.
 
Back
Top