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?

TK.
  • 46,577
  • 46
  • 119
  • 147

3 Answers3

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

H.B.
  • 166,899
  • 29
  • 327
  • 400
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).

Teoman Soygul
  • 25,584
  • 6
  • 69
  • 80
  • 2
    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. – CodeNaked Jun 07 '11 at 13:21
  • 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. – Teoman Soygul Jun 07 '11 at 13:23
  • 2
    You make a lot of assumptions, not all windows in an application necessarily belong to one main window. – H.B. Jun 07 '11 at 13:25
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.

Botz3000
  • 39,020
  • 8
  • 103
  • 127