Suspending tips for Windows 8 store applications with C#

Posted: (EET/GMT+2)

 

Windows 8 store applications work similar to Windows Phone 7 and 8 applications in the sense that on a high level, only a single application can run in any given instant. For Windows 8 store applications, this means that when you switch from one to another store app, the former app gets suspended, and might later on simply be terminated should the operating system choose to do so.

Now, when such suspending is taking place, the OS will notify your application and let it do some brief tasks, such as quickly saving state. The event you can handle in your .NET or HTML code is simply called Suspending, and most probably, you would be using the so-called application data APIs to save your app's state to the local disk. The good thing about these APIs is that the OS will keep the application running while it's waiting for these application data API calls to complete.

However, the time your suspending event handler allowed to run is limited: you have five seconds to complete whatever you want to accomplish inside the event handler. Otherwise, Windows will simply terminate your app.

Now, what if you need more time? Take a look at the class named SuspendingDeferral. With the help from this class, you can ask the operating system to give you a deferral object, which allows you to execute code beyond that short time limit.

To get an instance of this SuspendingDeferral class, you'd call the GetDeferral method of the SuspendingOperation class from inside the Suspending event handler as follows:

using Windows.ApplicationModel;
...

private async void App_Suspending(object sender, SuspendingEventArgs e)
{
  SuspendingDeferral deferral = e.SuspendingOperation.GetDeferral();

  // do some work here
  ...

  deferral.Complete();
}

Note that to tell the operating system that you are done, you'd call the Complete method:

deferral.Complete();

Hope this helps!