2

2つのプロセス間で通信しようとしています。MSDNのドキュメントから、MemoryMappingFileに出くわし、同じものを使用して通信しています。

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
    }

このコードが機能しない理由を誰かに教えてもらえますか?ディスクファイルで使用した場合と同じコードが機能します。

連続した読み取りと書き込みでは、データが失われているようです。私は何かが足りないのですか?

4

1 に答える 1

0

さて、私は問題を抱えています。

Windowによって自動的に処理されるように、MemoryMappedFileを破棄しないでおく必要があるようです。ですから、私が読み書きするとき、私は含めてはいけません

using(mf)

ブロック。これにより、共有メモリが削除されます。したがって、実際のコードは次のようになります。

 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);
            }
        }

とにかくありがとう。

于 2012-02-14T02:49:24.770 に答える