본문 바로가기
C#(CSharp)/Etc

How to properly exit a C# application?

by swconsulting 2018. 3. 29.

From MSDN:

Application.Exit

Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed. This is the code to use if you are have called Application.Run (WinForms applications), this method stops all running message loops on all threads and closes all windows of the application.

Environment.Exit

Terminates this process and gives the underlying operating system the specified exit code. This is the code to call when you are using console application.

This article, Application.Exit vs. Environment.Exit, points towards a good tip:

You can determine if System.Windows.Forms.Application.Run has been called by checking the System.Windows.Forms.Application.MessageLoop property. If true, then Run has been called and you can assume that a WinForms application is executing as follows.

if (System.Windows.Forms.Application.MessageLoop) 
{
    // WinForms app
    System.Windows.Forms.Application.Exit();
}
else
{
    // Console app
    System.Environment.Exit(1);
}


SOURCE : https://stackoverflow.com/questions/12977924/how-to-properly-exit-a-c-sharp-application



[WPF]


To exit your application you can call

System.Windows.Application.Current.Shutdown();

As described in the documentation to the Application.Shutdown method you can also modify the shutdown behavior of your application by specifying a ShutdownMode:

Shutdown is implicitly called by Windows Presentation Foundation (WPF) in the following situations:

  • When ShutdownMode is set to OnLastWindowClose.
  • When the ShutdownMode is set to OnMainWindowClose.
  • When a user ends a session and the SessionEnding event is either unhandled, or handled without cancellation.

Please also note that Application.Current.Shutdown(); may only be called from the thread that created the Application object, i.e. normally the main thread.

SOURCE : https://stackoverflow.com/questions/2820357/how-to-exit-a-wpf-app-programmatically

'C#(CSharp) > Etc' 카테고리의 다른 글

C# if/then directives for debug vs release  (0) 2018.04.07
C# directory exist or not  (0) 2018.04.02
int to string 4 digit (ex) 100 -> 0100  (0) 2018.02.19
Internet Feature Controls  (0) 2018.02.05
Convert webpage to image  (0) 2018.02.04