Monday, January 17, 2011

InvalidOperationException from IsolatedStorageSettings.Save on Windows Phone 7

I just had my first failed test from the marketplace certification for PhraseMeme Scanner v1.2. You can view the full error report here, but the important part is:

Comments: The application terminates unexpectedly when the user turns on/off one of the setting while trying to scroll to

another page.

Steps to reproduce:

1. Launch the application.

2. Scroll over to the setting menu.

3. At the same time, press and scroll on any of the settings.

4. Notice the application terminates unexpectedly when the user turns on/off one of the setting while trying to scroll to

another page.

The settings page uses ToggleSwitches from the Silverlight for Windows Phone Toolkit with a simple two-way binding to a values stored in an IsolatedStorageSettings class, so I was a bit confused where the error was coming from. Using Visual Studio I found that the IsolatedStorageSettings.Save method was throwing an InvalidOperationException whenever the user changed a setting and navigated way from the page at the same time.

The MSDN documentation doesn’t mention that the method can throw this error, but my guess is that either the value is in an indeterminate state or there is a conflict between the save method and the two-way binding. The error could have been there all along, but in this version I had moved all the IO calls to background threads to increase performance where as previously the exception was captured by a try/catch block on the calling method.

Luckily it was an easy fix: I added a try/catch statement to the save code block and inserted a delay to let whatever processing it was conflicting with finish before it tried to save the settings. Below is the new code that can be used for saving settings stored in an IsolatedStorageSettings class:

/// <summary>

/// Save settings to isolated storage. Will run using background thread to prevent blocking UI thread.

/// </summary>

public static void Save()


    ThreadPool.QueueUserWorkItem(func => {//Save items using background thread.



            //NOTE: may throw InvalidOperationException exception if user is in process of changing settings and navigating away from page




        catch (Exception ex)


            Debug.WriteLine("Error saving settings: " + ex);





Hope that helps someone prevent a failed submission to the marketplace.


Pawan said...

Thanks ... It helped me !!! Good work :)

Rohit said...

Thanks, it helped me, too. :)

Post a Comment

Blog.TheG2.Net - Your guide to life in the Internet age.