Reputation:
Is there a way to get the WaitHandle
from a MemoryMappedFile
? The assigned name seems to conflict with trying to fetch or create a Mutex using the same name.
const string name = "tobyd";
MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(name, 64);
Mutex mx = new Mutex(true, name); // bang! sadness.
If I use the Mutex.TryOpenExisting
static I get back false
and null in the out param. To no surprise.
What in MemoryMappedFile is using up this reference name? How would you wait on a MMF to be release to be able to re-use the name?
Upvotes: 1
Views: 1224
Reputation: 5070
Simplified a memory mapped file is a operative system construct for mapping a file into virtual memory, without reading the whole file from disk.
Instead it's accessing the actual medium (HDD, SSD, NAS, ...) as it was in memory. This is a cross process construct, to ensure no more than one instance (process/thread) writes to it simultaneously some kind of lock is needed.
Without knowing I would assume that Windows is using a Mutex with the mapName (filename) to solve this.
Edit
When decompiling the class MemoryMappedFile you will notice that it's using the windows kernel32 function CreateFileMapping which states that:
If lpName matches the name of an existing event, semaphore, mutex, waitable timer, or job object, the function fails, and the GetLastError function returns ERROR_INVALID_HANDLE. This occurs because these objects share the same namespace.
The argument mapName in the static method MemoryMappedFile.CreatOrOpen
will be passed on to lpName in the call to CreateFileMapping
If that statement is true, this code will also fail:
const string name = "tobyd";
Mutex mx = new Mutex(true, name);
MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(name, 64); // bang! sadness.
In light of that I think my original assumption was right.
Upvotes: 2