What is the preferred method of programmatically closing a C# WPF Application?
Asked Answered
S

3

9

Which is the preferred method of closing a C# WPF Application?

1) calling Window.Close() within the Main Window

2) Calling Application.Current.Shutdown( 0 ) within the Main Window.

Are the two semantically equivalent or is there a subtle distinction that I need to be aware of?

Smaltite answered 7/6, 2011 at 13:14 Comment(0)
P
5

The first only closes the window, depending on your Application.ShutdownMode that may not even shutdown the application.

How you exit the application depends solely on what you want to do, i for one tend to define the Application.MainWindow and set the ShutdownMode to OnMainWindowClose so all the small dialogues do not prevent the application from closing (since the default is OnLastWindowClose).

Platino answered 7/6, 2011 at 13:16 Comment(0)
C
3

Definitely Window.Close(); This will give all other windows to properly shut down and finalize their disposable resources. Note that you should call this on main window to close the entire app (i.e. this.Close(); from the main window).

Capello answered 7/6, 2011 at 13:17 Comment(3)
Close doesn't work in all cases though. There could be background threads or other top-level windows open, which would prevent the application from shutting down.Charpentier
When Window.Close(); is called from the main windows, all child windows are signaled to close (actually their Close() functions are called). I'm also assuming that threads are properly terminated on OnClosing() events as usual.Capello
You make a lot of assumptions, not all windows in an application necessarily belong to one main window.Platino
B
0

Application.Shutdown closes all open windows and disposes them, also you have the possibility to return another exit code. So I'd (usually) go with Application.Shutdown.

Bouquet answered 7/6, 2011 at 13:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.