views:

2913

answers:

3

My winforms app isn't shutting down nicely when I log off/shutdown. I have a main form, whose Closing event is fired correctly, but there must be something else keeping my application around. If I check Application.OpenForms there's just my one main form.

The tricky bit, and where the problem probably lies, is that my application uses ShellWindows to hook into Internet Explorer, and occassionally opens up forms when IE events fire. It's after one or more of these forms has been opened and closed that my app stops closing on shutdown.

I think I'm cleaning up all form objects etc and calling FinalReleaseComObject() appropriately, but I guess there are references somewhere that are holding my process open. Is there any way to work out what it is that's stopping my app from closing gracefully?

+2  A: 

An application will also stay open if there are threads running that have not been set to background. If you are creating any of your own threads, make sure that they are terminating appropriately.

If it is not critical that the thread finishes, set IsBackground to true. You can also call Abort on a thread to (somewhat)forcibly kill it.

Bearddo
I'm not starting any threads on my own, but I do get callbacks from various IE threads. So my code executes on multiple threads but I don't start them so I guess it's not my job to stop them.
Rory
Have you check to make sure that all of your callbacks from IE do return control back to IE? You can also check what threads are running in your app in Visual Studio (Debug->Windows->Threads). Obviously, it may not be a thread thing, but it's one place to look.
Bearddo
A: 

The most likely cause is that you have a background thread hanging around that is not being closed when the main window of your application is closed. Depending on your settings and framework version background threads can keep an application alive when the main thread is terminated.

During shutdown windows asks every running app to terminate usually by sending a WM_QUIT to the main window on a process. WinForms will happily use this message to shutdown the main window but if any background threads are left the actual process could continue.

JaredPar
A: 

This is a really ugly way to do this, but if all you want to do is kill any thread that's hanging around, you can get all the threads running in your application with System.Diagnostics.Process.GetCurrentProcess.Threads, and then enumerate through them and call Thread.Join() or Thread.Abort() on them.

Just make sure to NOT call .Abort() on the main (UI) thread that you're working from (the one that receives the Closing event). So make sure to check that your current thread (System.Threading.Thread) is not the one you're aborting.

routeNpingme