2012-02-12 1 views
2

두 프로세스간에 통신을 시도하고 있습니다. MSDN 문서에서, 나는 MemoryMappingFile을 보았고 나는 이것을 사용하여 통신했다.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 
    } 

아무도이 코드가 작동하지 않는 이유를 말해 줄 수 있습니까? 디스크 파일과 함께 사용할 때와 동일한 코드가 작동합니다.

연속적인 읽기 및 쓰기에서 데이터가 손실 된 것처럼 보입니다. 내가 놓친 게 있니?

+0

아무도이 질문을 보지 못한 것 같습니다. 그렇지? – abhishek

+0

[DelayAllocatePages 매개 변수가 일부 시스템에서 예외를 발생시킨 것 같습니다.] 경고 (https://stackoverflow.com/questions/46083451/memorymappedviewstream-error-does-not-have-appropriate-access). 소량의 메모리를 다루고 있기 때문에 어쨌든 매개 변수는 필요하지 않습니다. (그냥 앞에 할당하십시오) 또한 T는 항상 같은 크기입니까? 그렇지 않은 경우 각 항목의 오프셋을 추적해야 할 수 있습니다. – millejos

답변

0

음, 문제가 있습니다.

MemoryMappedFile은 창에 의해 자동으로 처리 될 수 있도록 숨겨진 상태로 유지해야하는 것처럼 보입니다. 내가 읽거나 쓸 때, 나는 (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); 
      } 
     } 

어쨌든 고마워요.