I have an application that imports data from Excel. However, when I run the winforms app and I intrupt the application, using
System.Windows.Forms.Application.Exit(); I can still see the "MyAppName".vshost32.exe running in task manager.
When I exit the application in debug mode, the form closes, but the VS IDE is not "stopped".
How do I ensure the application ends correctly.
The process doesn't terminate because it still has foreground threads running.
If you create threads in your application you need to mark them as background threads or make sure they terminate when you want the application to exit.
Your call to
Application.Exit() is working fine. The
MyAppName.vshost32.exe executable is a host for debugging purposes. It runs whilst you have a project open in Visual Studio, regardless of if there is an active debugging session.
Update: Ok, I misunderstood. The above is true, but you're probably having problems with hung threads in the background. You need to terminate your threads to make it close properly. Asher's answer covers this. If you're just trying to do a super-hacky quick-and-dirty kill, you can use the following (though I take no responsibility for side effects, since it's extremely hacky):
Have you tried the more brutal
Application.Exit() just sends a message saying to shutdown; if the message never gets processed (for whatever reason), the application will stay running indefinitely.
From the MSDN documentation of
The Exit method stops all running message loops on all threads and closes all windows of the application. This method does not necessarily force the application to exit. The Exit method is typically called from within a message loop, and forces Run to return.
I had a similar problem caused by a third party tool that did not allow me to set the threads as Background. Polynomial had the right idea, but then syntax is like this: