当前位置: 动力学知识库 > 问答 > 编程问答 >

Exiting a C# winforms application

问题描述:

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):

System.Diagnostics.Process.GetCurrentProcess().Kill();

网友答案:

Have you tried the more brutal Environment.Exit() function?

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 Application.Exit():

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:

System.Diagnostics.Process.GetCurrentProcess().Kill();
分享给朋友:
您可能感兴趣的文章:
随机阅读: