문제

I am trying to communicate between two processes. From MSDN Documentation, I came across with MemoryMappingFile and I am using the same to communicate.

public class SmallCommunicator : ICommunicator
    {
        int length = 10000;
        private MemoryMappedFile GetMemoryMapFile()
        {

            var security = new MemoryMappedFileSecurity();
            security.SetAccessRule(
                new System.Security.AccessControl.AccessRule<MemoryMappedFileRights>("EVERYONE", 
                    MemoryMappedFileRights.ReadWriteExecute, System.Security.AccessControl.AccessControlType.Allow));

            var mmf = MemoryMappedFile.CreateOrOpen("InterPROC", 
                            this.length, 
                            MemoryMappedFileAccess.ReadWriteExecute, 
                            MemoryMappedFileOptions.DelayAllocatePages, 
                            security, 
                            HandleInheritability.Inheritable);

            return mmf;

        }

        #region ICommunicator Members

        public T ReadEntry<T>(int index) where T : struct
        {
            var mf = this.GetMemoryMapFile();
            using (mf)
            {
                int dsize = Marshal.SizeOf(typeof(T));
                T dData;
                int offset = dsize * index;
                using (var accessor = mf.CreateViewAccessor(0, length))
                {
                    accessor.Read(offset, out dData);
                    return dData;
                }
            }
        }

        public void WriteEntry<T>(T dData, int index) where T : struct
        {
            var mf = this.GetMemoryMapFile();
            using (mf)
            {
                int dsize = Marshal.SizeOf(typeof(T));
                int offset = dsize * index;
                using (var accessor = mf.CreateViewAccessor(0, this.length))
                {
                    accessor.Write(offset, ref dData);
                }
            }
        }

        #endregion
    }

Can anyone tell me why this code does not work. The same code when used with disk file works.

On successive Reads and writes the data seems to be lost. Am I missing something?

도움이 되었습니까?

해결책

Well, I got the problem.

It seems to be that the MemoryMappedFile need to be kept undisposed such that it will be handled automatically by the windows. So when I read or write, I must not include

using(mf)

block. This will remove the shared memory. So the actual code should be :

 public void WriteEntry<T>(T dData, int index) where T : struct
        {
            var mf = this.GetMemoryMapFile();
            int dsize = Marshal.SizeOf(typeof(T));
            int offset = dsize * index;
            using (var accessor = mf.CreateViewAccessor(0, this.length))
            {
                accessor.Write(offset, ref dData);
            }
        }

Thanks anyway.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top