Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
742 views
in Technique[技术] by (71.8m points)

c# - Right way to close WPF GUI application: GetCurrentProcess().Kill(), Environment.Exit(0) or this.Shutdown()

My GUI desktop-based WPF 4.0 (C# .Net 4.0) program works with SQL Server database. Each time when I run my application it creates a connection to SQL Server via ADO.NET Entity Framework and if SQL Server is not reachable it throws an exception and shows MessageBox with notification.

Now I want that after user read this message application will shut down. I found three ways to do this:

Process.GetCurrentProcess().Kill();

or

this.Shutdown(); // Application.Current.Shutdown()

or

System.Environment.Exit(0);

All of them work fine and do what I need — close application and kill application's process in Windows Task Manager.

I want to know:

  1. What is the difference between them?
  2. Which way will close my application faster?
  3. Which way to close application should I use?
  4. Is Application.Current.Shutdown() and this.Shutdown() the same way to close application?

Or maybe there is another, more suitable, way to close a WPF GUI application?

Application.Exit() doesn't work for me as I get the error:

The event 'System.Windows.Application.Exit' can only appear on the left-hand side of += or -=

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Application.Current.Shutdown() is the proper way to shutdown an application. Generally because fire the exit events that you can handle more

Process.GetCurrentProcess().Kill() should be used when you want to kill the application. more

Ad1. The nature of those methods are totally different. The shutdown process can be paused to end some operations, kill force the application to close.

Ad2. Probably Kill() will be the fastest way, but this is something like kernel panic.

Ad3. Shutdown because it fires the close event

Ad4. That depend what this is.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...