Search code examples
c#memory-mapped-files

How to detect if a MemoryMappedFile is in use


In C# 4.0, MemoryMappedFile has several factory methods: CreateFromFile, CreateNew, CreateOrOpen, or OpenExisting. I need to open the MemoryMappedFile if it exists, and if not, create it from a file. My code to open the memory map looks like this:

try
{
    map = MemoryMappedFile.OpenExisting(
        MapName,
        MemoryMappedFileRights.ReadWrite
        | MemoryMappedFileRights.Delete);
}
catch (FileNotFoundException)
{
    try
    {
        stream = new FileStream(
            FileName,
            FileMode.OpenOrCreate,
            FileAccess.ReadWrite,
            FileShare.Read | FileShare.Delete);
        map = MemoryMappedFile.CreateFromFile(
            stream, MapName, length + 16,
            MemoryMappedFileAccess.ReadWrite,
            null,
            HandleInheritability.None,
            false);
    }
    catch
    {
        if (stream != null)
            stream.Dispose();
        stream = null;
    }
}

It pretty much works the way I want it to, but it ends up throwing an exception on OpenExisting way too often. Is there a way to check whether the MemoryMappedFile actually exists before I try to do the OpenExisting call? Or do I have to deal with the exception every single time?

Also, is there a way to find out if the current handle is the last one to have the MemoryMappedFile open, to determine if the file will be closed when the current handle is disposed?


Solution

  • Hans Passant gave the answer that worked for me in the comments:

    This isn't a real problem, you need to work on step #2 to make the MMF actually usable. That requires at least one named mutex to control what process can write to the mapped memory. One of those processes has to be the boss, the arbiter if you will. It needs to start first.