2012-02-02 345 views
7

我的圖書館正在使用獨立存儲,但僅在需求時才這樣做。所以我使用Lazy<T>懶洋洋地創建獨立存儲

然而,這將引發:

System.IO.IsolatedStorage.IsolatedStorageException 「無法確定裝配授予的權限。」

Lazy是否會讓奇怪的線程混淆孤立的存儲初始化?

示例代碼:

using System; 
using System.IO.IsolatedStorage; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      var thisWorks = IsolatedStorageFile.GetMachineStoreForAssembly(); 
      thisWorks.Dispose(); 

      var lazyStorage = new Lazy<IsolatedStorageFile>(IsolatedStorageFile.GetMachineStoreForAssembly); 

      var thisFails = lazyStorage.Value; 
      thisFails.Dispose(); 
     } 
    } 
} 

完整的堆棧跟蹤:

System.IO.IsolatedStorage.IsolatedStorageException was unhandled 
    Message=Unable to determine granted permission for assembly. 
    Source=mscorlib 
    StackTrace: 
    Server stack trace: 
     at System.IO.IsolatedStorage.IsolatedStorage.InitStore(IsolatedStorageScope scope, Type domainEvidenceType, Type assemblyEvidenceType) 
     at System.IO.IsolatedStorage.IsolatedStorageFile.GetMachineStoreForAssembly() 
     at System.Lazy`1.CreateValue() 
    Exception rethrown at [0]: 
     at System.IO.IsolatedStorage.IsolatedStorage.InitStore(IsolatedStorageScope scope, Type domainEvidenceType, Type assemblyEvidenceType) 
     at System.IO.IsolatedStorage.IsolatedStorageFile.GetMachineStoreForAssembly() 
     at System.Lazy`1.CreateValue() 
     at System.Lazy`1.LazyInitValue() 
     at System.Lazy`1.get_Value() 
     at ConsoleApplication1.Program.Main(String[] args) in C:\Users\Andrew Davey\AppData\Local\Temporary Projects\ConsoleApplication1\Program.cs:line 19 
     at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) 
     at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) 
     at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() 
     at System.Threading.ThreadHelper.ThreadStart_Context(Object state) 
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) 
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) 
     at System.Threading.ThreadHelper.ThreadStart() 
    InnerException: 

回答

6

看起來它是因爲你在MethodGroup傳遞(而不是委託/λ直接),這是無法找出電話最初來自哪裏。如果將其切換爲:

var lazyStorage = new Lazy<IsolatedStorageFile>(() => IsolatedStorageFile.GetMachineStoreForAssembly()); 

它應該可以正常工作。