关闭后 WPF 应用程序仍在后台运行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3543704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 22:03:20  来源:igfitidea点击:

WPF Application still runs in background after closing

wpf.net-4.0c#-4.0visual-c#-express-2010

提问by Jamie Keeling

This is slightly related to the question asked here yet the answer does not apply to my case as I am not using threads:

这与此处提出的问题略有相关,但答案不适用于我的情况,因为我没有使用线程:

WPF Not closing properly

WPF 未正确关闭

I have converted one of my WinForm application to a WPF application, nothing drastic needed to be done except for change a few words to the WPF/C# 4.0 equivalents (MessageBoxButtons to MessageBoxButton, why the one letter difference?).

我已将我的 WinForm 应用程序之一转换为 WPF 应用程序,除了将几个词更改为 WPF/C# 4.0 等效项(MessageBoxButtons 到 MessageBoxButton,为什么一个字母的区别?)之外,不需要做任何激烈的事情。

Anyway, if I run the application through the debugger it runs fine until I come to close it with the "X" button to the top right of the window. The application window closes but I noticed that the debugger still shows the stop icon, checking in the Task Manager confirms it is still running.

无论如何,如果我通过调试器运行应用程序,它运行良好,直到我用窗口右上角的“X”按钮关闭它。应用程序窗口关闭,但我注意到调试器仍然显示停止图标,检查任务管理器确认它仍在运行。

I am not running any other threads in the background so I know it's not waiting for something else.

我没有在后台运行任何其他线程,所以我知道它不会等待别的东西。

I've only just started with WPF but I assumed that when the user closes the application then it should just...close?

我刚刚开始使用 WPF,但我认为当用户关闭应用程序时,它应该只是...关闭?

Thanks for the help!

谢谢您的帮助!

回答by Kent Boogaart

What is your shutdown mode? If it's explicit, then it's because you're not explicitly shutting down. If it's main window, it's because you've not assigned the main window to Application.MainWindow.

你的关机模式是什么?如果它是明确的,那是因为您没有明确关闭。如果是主窗口,那是因为您没有将主窗口分配给Application.MainWindow.

回答by Shivanhsu Verma

Write this code on application closing button:

在应用程序关闭按钮上编写此代码:

Application.Current.Shutdown()

回答by Shadrack Kimutai

alternatively, add this to your App.cs

或者,将此添加到您的 App.cs

public App()
    {
        ShutdownMode = ShutdownMode.OnLastWindowClose;
    }

Detailed explanation here

详细解释在这里