Home > other >  Are multiple memory mapped files bugged?
Are multiple memory mapped files bugged?

Time:04-02

when adding a second memory mapped file to my project the first one no longer works cross processes.

Imports System.IO.MemoryMappedFiles

Module IPC
    Private ReadOnly _QlCtxOpen As MemoryMappedViewAccessor = MemoryMappedFile.CreateOrOpen("IPC_QlCtxOpen", 1).CreateViewAccessor()
    Public Property IsQlCtxOpen As Boolean
         Get
            Dim value As Boolean = _QlCtxOpen.ReadBoolean(0)
            Debug.Print($"QlCtxOpen {value}")
            Return value
        End Get
        Set(ByVal value As Boolean)
            _QlCtxOpen.Write(0, value)
            Debug.Print($"set QlCtxOpen to {value}")
        End Set
    End Property
End Module

when adding following line to the module the first mmf still works in the same process but a second process will no longer be able to read the correct value.

Private ReadOnly _alreadyOpenPID As MemoryMappedViewAccessor = MemoryMappedFile.CreateOrOpen("IPC_alreadyOpenPID", 4).CreateViewAccessor()

I know i should use a mutex for writing but in my project the write is triggered by mouse action so only 1 process will use it at the same time.

I don't understand what i'm doing wrong to break the first mmf, it works w/o the second mmf.

I'm using Microsoft Visual Studio Community 2019 Version 16.11.11 .NET Framework 4.7.2

CodePudding user response:

Turns out garbage collection is the culprit here. To fix this behavior make sure to have a reference to the memory-mapped file for as long as you need the value to be read by other processes.

Why it still worked with only 1 declaration and no reference to the memory-mapped file is a mystery to me.

  • Related