找不到MemoryMappedFile

时间:2013-02-08 14:16:19

标签: c# filenotfoundexception memory-mapped-files

这是我的问题:

我有一个WPF应用程序,其中包含List<MyObject>。 应用程序触发将程序集注入另一个WPF应用程序。 在注入开始之前,我想将List<MyObject>存储为序列化Byte[] 所以这是我的WPF应用程序的代码片段:

MyObject testObj = new MyObject();
SharedMemory<MyObject> shmem = new SharedMemory<MyObject>("TestMemory", 3000);
if(!shmem.Open())
    return;

shmem.Data = testObj;
shmem.Close();

SharedMemory.cs处理应存储的数据:

public class SharedMemory<T>
{
    #region Fields
    private String smName;
    private Mutex smLock;
    private int smSize;
    private Boolean locked;
    private MemoryMappedFile mmf;
    private MemoryMappedViewAccessor accessor;
    #endregion Fields

    #region Properties
    public T Data
    {
        get
        {
            Byte[] deSerializedBytes = new Byte[accessor.ReadInt32(0)];
            accessor.ReadArray<Byte>(4, deSerializedBytes, 0, deSerializedBytes.Length);
            return (T)ObjectSerializator.DeserializeItem<T>(deSerializedBytes);
        }
        set
        {
            smLock.WaitOne();
            Byte[] serializedBytes = ObjectSerializator.SerializeItem(value);
            accessor.Write(0, serializedBytes.Length);
            accessor.WriteArray<byte>(4, serializedBytes, 0, serializedBytes.Length);
            smLock.ReleaseMutex();
        }
    }
    #endregion Properties

    #region Constructors
    /// <summary>
    /// Default constructor of SharedMemory class
    /// </summary>
    public SharedMemory(String pName, int pSize)
    {
        smName = pName;
        smSize = pSize;
    }
    #endregion Constructors

    #region Public Methods

    public bool Open()
    {
        try
        {
            // Create named MMF
            try
            {
                mmf = MemoryMappedFile.OpenExisting(smName);
            }
            catch(Exception)
            {
                mmf = MemoryMappedFile.CreateNew(smName,smSize);
            }

            // Create accessors to MMF
            accessor = mmf.CreateViewAccessor(0, smSize, MemoryMappedFileAccess.ReadWrite);

            // Create lock
            smLock = new Mutex(true, "SM_LOCK", out locked);
        }
        catch
        {
            return false;
        }

        return true;
    }

    public void Close()
    {
        accessor.Dispose();
        mmf.Dispose();
        smLock.Close();
    }
    #endregion Public Methods

    #region Private Methods
    #endregion Private Methods
}

存储后(调试时我在set accessor.ReadInt32(0)Data之后进行了测试,如果我的get方法有效,并且工作正常!),我继续注入和最后,我想阅读注入的WPF应用程序上最近存储的数据:

   SharedMemory<TestExecutionConfiguration> shmem = new SharedMemory<TestExecutionConfiguration>("TestMemory", 3000);
   if(!shmem.Open())
       return false;

   TestExecutionConfiguration test = shmem.Data;
   shmem.Close();

但是在Assemly内部调用的shmem.Open()注入第二个WPF应用程序,我得到FileNotFoundException,而SharedMemory类将创建一个新的MemoryMappedFile,所以我无法阅读第一份申请表保存的内容。 为什么找不到我的SharedMemory?

0 个答案:

没有答案