Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Application.Current.Exit() and OnSuspendingEvent

In Universal Windows 10 C#/Xaml Application when I close my app via Alt+F4 OnSuspending event is fired. Although, when I call Application.Current.Exit() this is not the case, despite the documentation states that this event is fired whenever app is about to be terminated.

Why is this the case? It looks like inconsistent behaviour which caused bug in my app.

like image 454
xcoder37 Avatar asked Jan 18 '26 23:01

xcoder37


2 Answers

This official graphic by Microsoft illustrates the application lifecycle for a Windows Universal Platform app:

Lifecycle

The documentation of this lifecycle explains:

After an app has been closed by the user, it's first suspended and then terminated, and enters the NotRunning state.

Further more, Microsoft recommends to NOT close the app programatically!
From "Guidelines for app suspend and resume":

Don't include Close buttons or offer users other ways to terminate your app in its UI. Users should feel confident that the system is managing their apps for them. The system can terminate apps automatically to ensure the best system performance and reliability, and users can choose to close apps using gestures on Windows or through the Task Switcher on Windows Phone.

But if you...

close an app programmatically, the system treats it as an app crash.

Therefore, your app will go from a Running state, directly into a NotRunning state.

You might be able to observe this behavior if you handle the Exiting event of the CoreApplication class.

like image 99
Herdo Avatar answered Jan 21 '26 01:01

Herdo


  1. Microsoft does not recommend to exit application from code:

Use this method to provide UI that enables users to exit your app. Normally, however, you should not provide this UI because the system automatically manages app lifetime and terminates suspended apps as needed to free resources.

  1. Application.Exit does not suspend application, but shutdown it - that's why your code in OnSusspending is not called
  2. Workaround: in your App.cs add

a) using Windows.ApplicationModel.Core;

b) in App constructor add CoreApplication.Exiting += CoreApplication_Exiting;

c) write CoreApplication_Exiting method

private void CoreApplication_Exiting(object sender, object e)
        {
            //HERE your code
        }

it will run all time when application terminates.

like image 35
Sergiu Cojocaru Avatar answered Jan 21 '26 02:01

Sergiu Cojocaru