IsolatedStorageSettings throws an IsolatedStorageFileStream when I try to get value

≡放荡痞女 提交于 2019-12-06 07:59:37

It appears that this exception can be the result of accessing IsolatedStorageSettings.ApplicationSettings from multiple threads (which would include the completion handler for HTTP requests).

I assume IsolatedStorageSettings keeps a shared Stream internally so multiple readers causes it to enter an invalid state.

The solution is simply to serialize access to the settings. Any time you need access to your settings, make it happen on the UI thread (via Dispatcher.BeginInvoke) or use a lock:

public static class ApplicationSettingsHelper
{
    private static object syncLock = new object();

    public static object SyncLock { get { return syncLock; } }
}

// Later

lock(ApplicationSettingsHelper.SyncLock)
{
    // Use IsolatedStorageSettings.ApplicationSettings
}

Alternatively, you could hide the lock by using a delegate:

public static class ApplicationSettingsHelper
{
    private static object syncLock = new object();

    public void AccessSettingsSafely(Action<IsolatedStorageSettings> action)
    {
        lock(syncLock)
        {
            action(IsolatedStorageSettings.ApplicationSettings);
        }
    }
}

// Later
ApplicationSettingsHelper.AccessSettingsSafely(settings =>
{
    // Access any settings you want here
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!