Лениво создавая изолированное хранилище - PullRequest
8 голосов
/ 02 февраля 2012

Моя библиотека использует изолированное хранилище, но делает это только по требованию. Поэтому я использую 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: 

1 Ответ

7 голосов
/ 02 февраля 2012

Похоже, это потому, что вы передаете MethodGroup (а не делегат / лямбда напрямую), и он не может определить, откуда исходил вызов. Если вы переключите его на это:

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

Все должно работать нормально.

...