views:

99

answers:

3

I have one background thread I use for processing separately from the GUI, and everything works fine between the threads. However when I close the application, the program "closes" but does not kill the process. The background thread is keeping the program alive it seems.

I have set "myThreadInstance.IsBackground = true;", and I thought this would require C# to kill it when it is killed.

I am testing this all in Visual Studio (2010, using .NET 4.0), and after the first build, the rest all fail because the exe is still in use so it cannot overwrite it. Looking in task manager, it is there. Killing Visual Studio releases the vbhost process which releases my exe. Killing my exe's process, makes vbhost respawn it in a second or two.

A: 

This type of problem usually requires code to figure out. Take your app and trim it down to the bare minimum necessary to show the issue.

However, most likely you are either not signaling the thread to terminate or the thread is such a long running beast that it doesn't ever see the signal.

Chris Lively
But that is the point of isBackground being true. You should not have to do anything, .NET should automatically kill it.
Nick
As Sidharth said below, you can not rely on the framework to clean up after you. The only way to be really sure is to do it yourself. Regardless, if the thread doesn't respond to the signal, then it will keep going...
Chris Lively
A: 

Try using Application.Exit(0); in the form_closing/form_closed event.

Bug: I think this might be a bug. Look at the comments at the bottom of this MSDN page: http://msdn.microsoft.com/en-us/library/system.threading.thread.isbackground.aspx

Also, try using the BackgroundWorker. Here's a good description in the VisualStudio Magazine: http://visualstudiomagazine.com/articles/2007/09/01/simplify-background-threads.aspx

Sidharth Panwar
I tried using a BackgroundWorker, and the same thing happens. So that's when I switched it to Threads which worked fine for me before in another application. I am not sure what the difference is, and why this would now hang the process...
Nick
I can't be sure without seeing what's happening in code but one thing's clear that we can't rely on the framework to kill the background thread (as it should be doing.) So, to resolve this thing you might need to resort to a hack or something. Try firing an Abort on the background thread when you want to close the app. Also is Application.Exit(0); not working?
Sidharth Panwar
A: 

Actually, based on your description and other things you've tried (and their results), I believe the most likely cause is this:

You have another foreground thread in your application, other than the one you're examining.

Stephen Cleary