Meirion Hughes
Meirion Hughes

Reputation: 26408

Keep a MemoryMappedFile Alive after Dispose

I need to access a shared memory map file (created and owned by a separate program); To do so I'm using

_map = MemoryMappedFile.OpenExisting(
            "buffer",
            MemoryMappedFileRights.ReadWrite, 
            HandleInheritability.None);

_mapAccessor = _map.CreateViewAccessor(0, 0, MemoryMappedFileAccess.ReadWrite);

When I close the application I call dispose on these:

public void Dispose()
{
    if (_mapAccessor != null)
        _mapAccessor.Dispose();

    if (_map != null)
        _map.Dispose();
}

but it seems like something I'm doing here is killing off the memory map file, because the other program that uses this starts getting protected memory faults.

If I dispose the _map does it actually destroy the memory mapped file, even though its not inherited ownership?

Update

Turns out the other program, not under my control, was doing naughty things after I had signaled it to go-to idle mode (immediately before disposing the memory map).

When using 'MemoryMappedFile.OpenExisting' with 'HandleInheritability.None' the memory map file will not be destroyed after dispose.

Upvotes: 9

Views: 2552

Answers (1)

Matthew Watson
Matthew Watson

Reputation: 109587

No, disposing a MemoryMappedFile opened by calling OpenExisting() will not destroy the underlying MMF.

The process that called the Windows API CreateFileMapping() controls the lifetime of the MMF and OpenExisting() calls OpenFileMapping() instead.

Upvotes: 4

Related Questions