Form close and BackgroundWorker

I have a BackgroundWorker retriving data to a report viewer and it takes a minute or so.

What should I do for when the user closes the form (MDIChild) during the life of the BackgroundWorker

I added BackgroundWorker.CancelAsync() in the formclosing event and it seam to work, but when you exit the application you get an error.




Answer this question

Form close and BackgroundWorker

  • MarkWHarrison

    You are saying I have to let the BackgroundWorker finish

    I prefer the user will see the form close right away.



  • Bruff

    Hi,

    In the FormClosing event of the main application wait until the IsBusy property of the BackgroundWorker becomes FALSE.

    A better implementation is to cancel the form closing and to start a custom timer which checks every N milliseconds the IsBusy property.

    You may also test whether the CloseReason property of the FormCloseEventArgs is equal with ApplicationExitCall to stop the execution until the BackgroundWorker finishes its work.

    Best.


  • flo2007

    You can hide the form while you're waiting, to give the user responsive feedback.

    If your BackgroundWorker thread takes a while to cancel, you might think about checking for cancel more often.

    If the form has hooked up some event handlers to the BackgroundWorker thread, you cannot let it close before the BackgroundWorker is done; otherwise the BackgroundWorker will be calling into an object that is in an unknown state.

    You could try and remove the event handlers that were hooked up to the BackgroundWorker before closing; but, it's best to wait for the worker to complete.



  • ShowMethodHang

    The long operation is one statement (long query) so I did not have much of a way to check for cancel.

    I took out the BackgroundWorker.CancelAsync() from the formclosing event, and now it works fine.

    I guess by closing the form the BackgroundWorker itself is disposed of so it cannt complain.

    Thanks for the input.



  • Form close and BackgroundWorker