August 19, 2017

Develop for Windows 10 Q&A – (7) Application Life Cycle

ja

 

This Q&A is related to video #13 (Application Life Cycle) in Jerry Nixon and Andy Wigley’s A Developer’s Guide for Windows 10.

Q. What is application life cycle?

A. An application can only be in one of the following three states:

Running <=> Suspended -> Terminated (Not Running)

cyc

Apps get suspend when user click Windows Button, answer a phone call, or other events get app suspended. A suspended app can get terminated by the OS in low memory condition. A running app is usually terminated by user action.

Q. What is a suspended state?

A. A suspended app is not using CPUs and other resources. But it’s still in the memory space. If there are too many apps in suspended status that use too much memory, the system can decide to take some suspended app out of memory, so it is terminated.

There is no hard limit of how many apps can be in the suspended state, but there is a limited of 8 concurrent background tasks running at the same time.

 

Q. Rules in state transitions

A. The following chart give a full picture of all state changes, memory usage, and time limits in suspending an app.

mem

To note: there is 5 sec max for programmer to save status before get suspended.

Desktop family apps are suspended when they are minimized. That’s interesting. Note here it doesn’t refer to the desktop program or Win32 program.

Q. How to handle app suspension in the code?

A. Handle suspending event: usually save program state, and data. Handle Resuming event to load state and data back to the program.


public App()
{
this.InitalizeComponent();
this.Suspending += (s,e) =>
{
//save data
};
this.Resuming += (s, e) =>
{
//load data
};
}

>> Visual Studio has a lifecycle events in debug state. It can help to create suspension,resuming and termination events in debug.

Q. What is extended execution?

A. Normally, when the OS suspend an app for any reason, the suspension will be done in 5 seconds, but you can ask to extend that, it is called extended execution.

There are two cases you want to do that: 1) you have critical data that takes more than 5 sec. 2) Some apps want to keep running while switching to another task, like turn by turn navigation app.

Remember: this is not 100% reliable, because you are not guaranteed your request to be granted.

private async void OnSuspending(object sender, SuspendingEentArgs args)
{
var deferral = e.SuspendingOperation.GetDeferral();
using(var session = new ExtendedExecutionSession{Reason =  ExtendedExecutionReason.SavingData })
{
session.Description = "Upload Data";
session.Revoked += (s, e) => { Log("Save incomplete"); };
try
{
if(await session.RequestExtensionSync() == ExtendedExecutionResult.Denied)
UploadBasicData();
else
await UploadDataAsync(session);
Log("Save complete");
}
catch {Log("Save failed");}
finall { deferral.Complete();}
}