Public musings, often on software development RSS 2.0
# Wednesday, October 15, 2008

I ran into some code today which caught me off guard.  In the event handler for the Exit menu item was the command:

Application.Current.Shutdown()

(Note I've omitted the ; for C# syntax vs VB)

Now traditionally I've always used:

Close()

(I've omitted the 'this' or 'me' as well as the ; for those looking for language specifics...)

So is there a difference and is one better?  Well there is definitely a difference and in my opinion each is definitely better in a certain scenario.

The core similarlity is that both need to be called from your main application window thread in order to shut the application.  Thus calling close on a dialog doesn't shutdown your application, although calling shutdown from your main thread even in a dialog will...  each will also call all the appropriate events for closeing windows and disposing of objects.

The core difference comes down to how your main application thread responds to the events which are fired as it prepares to close.  The Shutdown command is unstoppable the app will close regardless of what one of the event handlers attempts.  However, the Window_Closing (in WPF) event allows you to update the status of the CancelEventArgs (e) to indicate that the shutdown should be prevented.  Thus if for example the user asked to exit and then the app said "but you have unsaved changes Save, Continue, Cancel?" which is something typically caught in the Window Closing event (since it's triggered when you click that cute little X in the upper right corner to close your window). 

The problem - if you've called Shutdown, it doesn't matter if the user says - "Cancel" your app is slamming down. 

Thus unless you are attempting to handle a sudden error condition ("Must stop now to avoid corrupting data.") you probably want to rely on the Window.Close() method instead of the Application.Shutdown method.

Wednesday, October 15, 2008 4:05:55 PM (Pacific Daylight Time, UTC-07:00)  #    Comments [0] -
.NET | Technology | Visual Basic
Comments are closed.
Archive
<September 2010>
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Bill Sheldon
Sign In
All Content © 2010, Bill Sheldon