2012-02-01 68 views
2

我試圖得到一個布爾值,我使用isolatedStoragesettings這樣就節省:IsolatedStorageSettings拋出IsolatedStorageFileStream當我嘗試獲得價值

IsolatedStorageSettings.ApplicationSettings.TryGetValue(KEYSTRING, out myBoolValue); 

但我只得到這個例外,當我調試 不允許操作上IsolatedStorageFileStream。

當我使用(無需調試運行)Ctrl + F5它工作得很好。任何想法這裏錯了什麼?

+0

這是否發生在仿真器和/或實際設備中?設備上的 – 2012-02-01 15:11:10

+0

。只在調試 – Qirat 2012-02-01 16:53:10

+0

,它在模擬器上工作? – 2012-02-01 17:38:47

回答

3

appears此異常可能是由多個線程(其中包括HTTP請求的完成處理程序)訪問IsolatedStorageSettings.ApplicationSettings的結果。

我假設IsolatedStorageSettings在內部保持共享Stream,所以多個閱讀器導致它進入無效狀態。

解決方案只是序列化訪問設置。您需要訪問您的設置,任何時候做到這一點的UI線程(通過Dispatcher.BeginInvoke)或使用鎖:

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

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

// Later 

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

或者,你可以通過使用代理隱藏鎖:

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 
}); 
+0

+1你的答案,但我不得不懷疑這是否解決了UI線程的重入問題,並且消息泵經常會導致此類併發訪問。 – Hong 2014-04-03 02:35:58