Search code examples
c#disposememory-mapped-files

Correct way to dispose memory mapped files in C#


I have the following test code:

const string filePath = @"c:\tests\mmap.bin";
const long k64 = 64 * 1024;

// create mmap file and accessor, then adquire pointer 
var fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
fileStream.SetLength(k64);

var mmap = MemoryMappedFile.CreateFromFile(fileStream, null, fileStream.Length,
    MemoryMappedFileAccess.ReadWrite,
    null, HandleInheritability.None, true);

var accessor = mmap.CreateViewAccessor(0, 0, MemoryMappedFileAccess.ReadWrite);
byte* pointer = null;
accessor.SafeMemoryMappedViewHandle.AcquirePointer(ref pointer);


// dispose accessor,  mmap file and stream
accessor.SafeMemoryMappedViewHandle.Close();
accessor.Dispose();
mmap.SafeMemoryMappedFileHandle.Close();
mmap.Dispose();
fileStream.Dispose();

// This causes UnauthorizedAccessException: 
// Access to the path 'c:\tests\mmap.bin' is denied
File.Delete(filePath);

It creates or opens c:\tests\mmap.bin, set its length to 64Kb, memory maps it, and then tries to release all resources. But not all resources are released, File.Delete(filePath) fails.

Which is the correct way to release all resources held by memory mapped files?


Solution

  • After

    accessor.SafeMemoryMappedViewHandle.AcquirePointer(ref pointer);
    

    you need to call

    accessor.SafeMemoryMappedViewHandle.ReleasePointer();
    

    for cleanup.