Search code examples
c#winformsbackgroundworker

Cancelling Background Tasks


When my C# application closes it sometimes gets caught in the cleanup routine. Specifically, a background worker is not closing. This is basically how I am attempting to close it:

private void App_FormClosing(object sender, FormClosingEventArgs e) { backgroundWorker1.CancelAsync(); while (backgroundWorker1.IsBusy) ; // Gets stuck here. }

Is there a different way that I should be doing this? I am using Microsoft Visual C# 2008 Express Edition. Thanks.

ADDITIONAL INFORMATION:

The background worker does not appear to be exiting. This is what I have:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
   while (!backgroundWorker1.CancellationPending)
   {
      // Do something.
   }
}

I've also modified the cleanup code:

private void App_FormClosing(object sender, FormClosingEventArgs e)
{
   while (backgroundWorker1.IsBusy)
   {
      backgroundWorker1.CancelAsync();
      System.Threading.Thread.Sleep(1000);
   }
}

Is there something else that I should be doing?


Solution

  • Kevin Gale is correct in stating that your BackgroundWorker's DoWork handler needs to poll for CancellationPending and return if a cancellation is requested.

    That being said, if this is happening when your application is shutting down, you can just ignore it safely, as well. BackgroundWorker uses a ThreadPool thread, which is, by definition, a background thread. Leaving this running will not prevent your application from terminating, and the thread will automatically be torn down when your application shuts down.