退出 WPF 应用程序的最佳做法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26395237/
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
what is the best practice to exit an WPF application?
提问by sqr
I am maintaining an existing C# application, and I noticed the following code are not working as expected.
我正在维护一个现有的 C# 应用程序,我注意到以下代码没有按预期工作。
private void Form1_Load(object sender, EventArgs e){
...
if (proc.Length == 0)
{
proc = Process.GetProcessesByName("OpCon");
if (proc.Length == 0)
{
WriteLog("DataloggerService start: no TSS process detected; close;");
this.Close();
}
}
...
}
The code is supposed to exit after the Close() api call. However, it still proceed.
代码应该在 Close() api 调用后退出。然而,它仍在继续。
After some reading and research, I modified it to
经过一些阅读和研究,我将其修改为
private void Form1_Load(object sender, EventArgs e){
....
if (proc.Length == 0)
{
proc = Process.GetProcessesByName("OpCon");
if (proc.Length == 0)
{
WriteLog("DataloggerService start: no TSS process detected; close;");
this.Dispose();
Environment.Exit(0);
}
}
....
}
It seems to exit as expected. However, I am not confident whether this is the best practice?
它似乎按预期退出。但是,我不确定这是否是最佳实践?
is it really necessary to call this.Close() or this.Dispose() before Environment.Exit()?
真的有必要在 Environment.Exit() 之前调用 this.Close() 或 this.Dispose() 吗?
Thanks.
谢谢。
regards, Sqr
问候,平方
回答by jadavparesh06
In your WPF application whenever your MainWindow that is specified as StartupURI in App.xaml is closed your application exits automatically.
在 WPF 应用程序中,只要在 App.xaml 中指定为 StartupURI 的 MainWindow 关闭,您的应用程序就会自动退出。
Still if you want to handle this exit of application on your end you can go for below solution.
尽管如此,如果您想最终处理此应用程序退出,您可以使用以下解决方案。
Override the onClosing of MainWindow and manually exit/shutdown your application.
覆盖 MainWindow 的 onClosing 并手动退出/关闭您的应用程序。
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
// Shutdown the application.
Application.Current.Shutdown();
// OR You can Also go for below logic
// Environment.Exit(0);
}

