The process that created the memory mapped file should contain a link to it as long as you want it to live. Using CreateOrOpen bit complicated for this purpose - you do not know if you are going to destroy a file with memory mapping or not.
You can easily see this at work by adding explicit mmf.Dispose() to your WriteToMemoryFile method - it will completely close the file. The Dispose method is called from the finalizer of the mmf instance some time after all references to it fall out of scope.
Or, to make it even more obvious that the GC is the culprit, you can try explicitly invoking the GC:
WriteToMemoryFile("Hi"); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); ReadFromMemoryFile().Dump();
Note that I slightly modified the methods to work with simple strings; you really want to create the simplest possible code that reproduces the behavior you observe. Even just getting JsonConverter is an unnecessary complication and might make people not even try to run your code :)
And as a side note, you want to Mutex.WaitOne AbandonedMutexException when you make a Mutex.WaitOne - this is not a failure, so you took the mutex. Most applications handle this incorrectly, which leads to deadlock issues, as well as ownership of the mutex and life cycle :) In other words, treat AbandonedMutexException as a success. Oh, and it's a good idea to put things like Mutex.ReleaseMutex in a finally clause to make sure that this really happens, even if you get an exception. The thread or the process of the dead does not matter (this will simply cause one of the other participants to get an AbandonedMutexException ), but if you just get an exception that you are βhandlingβ with your return false; , the mutex will not be released until you close all your applications and start fresh again :)
source share