smixik
smixik

Reputation: 13

WinRT/UWP is suspending rising on power off?

I am trying to save data before application (WinRT 8.1) close/sleep/minimze (or windows shutdown/restart in tablet with WIN10) using app suspending event.

https://learn.microsoft.com/en-us/windows/uwp/launch-resume/suspend-an-app

However, it os not working on power off / shutdown WinRT/UWP: Is suspending action rising on long power off button holding?

Upvotes: 1

Views: 386

Answers (2)

Nico Zhu
Nico Zhu

Reputation: 32775

Is suspending action rising on long power off button holding?

System will shutdown forcibly with long press power off button. And the system could not make sure Current user session is finished. So the suspending event handler could not be invoked correctly.

From Windows 10 universal Windows platform (UWP) app lifecycle:

Current user session is based on Windows logon. As long as the current user hasn't logged off, shut down, or restarted Windows, the current user session persists across events such as lock screen authentication, switch-user, and so on.

So, before shut down, the app still in the Current user session. And Suspended will be invoked on power off(shut down).

Note, you can not test it in debug model within Visual Studio. Because when you shut down the system, Visual Studio will exit degbug model at first. The Suspended event will not be invoked as expect. You could verify with following code.

private void OnSuspending(object sender, SuspendingEventArgs e)
{
    var stringBulider = new StringBuilder();
    var deferral = e.SuspendingOperation.GetDeferral();

    Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
    Object value = localSettings.Values["exampleSetting"];
    stringBulider.Append(value.ToString() + "/Next");
    localSettings.Values["exampleSetting"] = stringBulider.ToString();

    deferral.Complete();
}

Each time you shut down, the stringBulider will be append one at a time.

Upvotes: 0

Martin Zikmund
Martin Zikmund

Reputation: 39072

The Suspending lifecycle event will fire in case of a normal OS shutdown - if you do Start -> Shut down.

This is unfortunately not the case with long power off button holding and restart button press, because both these are improper ways of shutting down your PC. Holding power button to shutdown essentially suddenly "cuts-down power" to the PC, which means the OS cannot respond to this and all unsaved data are lost. This method of shutting down a PC should be used only when something really bad happens and everything freezes. That is why the UWP app has no chance to run the suspending event handler in this case.

Upvotes: 1

Related Questions