Managing Tombstone State in a Windows Phone 7 Application

1 במאי 2011

4 תגובות

Before we continue, I trust that you know exactly the meaning of tombstone state in a Windows Phone 7 application. If this is not the case, simply read Yochay’s great posts on the application execution model (Part 1, Part 2, Part 3).

Every Windows Phone 7 application needs to manages tombstoning correctly to provide a better user experience and pass the application certification requirements.

When your application goes into tombstone state, it is your responsibility to save all the application and page state, so that when the page gets reloaded it can recover properly and reload the previous data. This was the user doesn’t even realizes that the application process got terminated and reloaded.

To ease the handling of the tombstone state I’ve created a simple StateManager class which helps serializing the data when going into tombstone state and deserializing the data when you get back.

How to Use StateManager?

Suppose your current page has the following data members you want to save across tombstoning:

  • LastPosts
  • Posts
  • Comments
  • Images

Now all you need to do is to save them when the application goes into tombstone state and reload them when it gets back from tombstone state.

Saving the Data

The proper place for the code that saves the data resides in the OnNavigatedFrom method. In this method you should call the helper extension method SaveState for each member of the page that you want to save, passing the value and the key on which to save it:

protected override void OnNavigatedFrom(NavigationEventArgs e)
{
    this.SaveState("LastPostsKey", LastPosts);
    this.SaveState("PostsKey", Posts);
    this.SaveState("CommentsKey", Comments);
    this.SaveState("ImagesKey", Images);
}

Loading the Data

The proper place for the code that loads the data when returning from tombstone state resides in OnNavigatedTo method. In this method you should call the helper extension method LoadState for each member of the page that you want to load, passing the key related to the member’s value:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    LastPosts = this.LoadState<ObservableCollection<RssItem>>("LastPostsKey");
    Posts = this.LoadState<ObservableCollection<RssItem>>("PostsKey");
    Comments = this.LoadState<ObservableCollection<RssItem>>("CommentsKey");
    Images = this.LoadState<ObservableCollection<ImageItem>>("ImagesKey");
}

Definition of StateManager

So how is the StateManager class defined? It is as simple as the following two extension methods:

/// <summary>
/// State Manager
/// </summary>
public static class StateManager
{
    /// <summary>
    /// Saves a key-value pair into the state object
    /// </summary>
    /// <param name="phoneApplicationPage">The phone application page.</param>
    /// <param name="key">The key.</param>
    /// <param name="value">The value.</param>
    public static void SaveState(this PhoneApplicationPage phoneApplicationPage, string key, object value)
    {
        if (phoneApplicationPage.State.ContainsKey(key))
        {
            phoneApplicationPage.State.Remove(key);
        }

        phoneApplicationPage.State.Add(key, value);
    }

    /// <summary>
    /// Loads value from the state object, according to the key.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="phoneApplicationPage">The phone application page.</param>
    /// <param name="key">The key.</param>
    /// <returns>The loaded value</returns>
    public static T LoadState<T>(this PhoneApplicationPage phoneApplicationPage, string key)
        where T : class
    {
        if (phoneApplicationPage.State.ContainsKey(key))
        {
            return (T)phoneApplicationPage.State[key];
        }

        return default(T);
    }
}

Note: this code was first published as part of the “Using Pivot and Panorama Controls” lab found in the Windows Phone Training Kit for Developers, which I wrote for Microsoft.

That’s it for now,
Arik Poznanski.

הוסף תגובה
facebook linkedin twitter email

כתיבת תגובה

האימייל לא יוצג באתר. (*) שדות חובה מסומנים

4 תגובות

  1. Gurpreet Singh Nagi4 בספטמבר 2011 ב 14:13

    Thank you so much for this article ! Gr8 explanation !

    להגיב
  2. Atul Gupta5 בספטמבר 2011 ב 15:57

    I don't think you directly reload in OnNavigateTo. You can do that, but it is unnecessary if the page instance is not new. Existing page instance means that its state is automatically restored and your calling state manager is an over head

    להגיב
  3. arik5 בספטמבר 2011 ב 22:45

    Atul Gupta, you are correct.
    The code was simplified. And also doesn't take into account Mango improvements.

    להגיב
  4. Varun22 בספטמבר 2011 ב 18:15

    In windows phone 7.1, there is state called dormant(apps are alive and is in background) – which is introduced to handle fast switching of apps. At max windows phone can store 5 tombstoned application data. so when an application is in tombstone means the application state is saved before garbage collected and is terminated. My question is: -Does this means when again start a fresh tombstoned application, will the state be restored ,if we have the state information present in the isolated storage?

    להגיב