Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 661
Meirion Hughes Avatar asked Jun 08 '13 18:06

Meirion Hughes


1 Answers

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.

like image 96
Matthew Watson Avatar answered Nov 16 '22 08:11

Matthew Watson