views:

305

answers:

2

I have a simple program that has backgroundworkers, and it runs with no stop, and no matter when I close it, it will always have some still running (or all of them) and I've noticed that closing the application doesn't completly kill it. After running it some times, there are processes (1 for each run) that remain on the process tab of the windows task manager.

Why do they remain? what do I do for them not to ?

ps.: I've read questions about backgroundworker's behavour in application closing, but I guess it's not acting as intended then. Any suggestions ?

A: 

Are they threads you spin up yourself? If you create your own threads I believe you need to set them to background threads in order to have them terminate along with the main thread. Otherwise they will keep the process alive. From memory the code to set a given thread to background is something like:

Thread t = new Thread(YouStartMethod);
t.IsBackground = true;
t.Start();

Hope this helps

soren.enemaerke
No, they are backgroundworker threads (I'm not sure I can say it like this, sorry) I don't start the threads myself.
MarceloRamires
+2  A: 

A better approach is to stop / kill the thread using an event or custom action before applicaion in closed.

like as follows

private void ButtonStopBGWorker_Click(object sender, RoutedEventArgs e)
{
 BackgroundWorker worker = sender as BackgroundWorker;
 if ((worker.CancellationPending == true))
   {
      e.Cancel = true;
      break;
   }
}

This post at the forum will give you more insight. Also, have a look at MSDN for details about how to manage Backgroundworker Threads

Hope it helps

Asad Butt