懒散地创建隔离存储

本文关键字:隔离 存储 创建 | 更新日期: 2023-09-27 18:22:10

我的库使用隔离存储,但仅在需要时使用。所以我使用Lazy<T>

然而,这抛出:

System.IO.IsolatedStorage.IsolatedStorage异常"无法确定为程序集授予的权限。"

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: 

懒散地创建隔离存储

看起来是因为您传入了MethodGroup(而不是直接传入委托/lambda),它无法确定调用的原始来源。如果你把它切换到这个:

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

它应该可以正常工作。