I\'ve made a simple test with a MemoryMappedFile
as msdn says :
2 processes, 1 memory mapped file :
You are battling an implementation detail of BinaryWriter.Write(string). It writes the length of the string first, required so that BinaryReader knows how many characters it needs to read when reading the string back. For short strings, like "1", it writes a single byte to store the length.
So the offset you pass to CreateViewStream() is wrong, passing 1 will make it overwrite part of the string written by process A. The smiley character you see is the glyph for (char)1. The length byte of the string written by process B.
Memory mapped files are troublesome in managed code. You normally read and write to them by declaring a struct to set the layout and using pointers to access the view but that requires unsafe code. Streams are a pretty poor abstraction for a chunk of memory but a necessary evil. Also the reason it took so long for MMFs to become available in .NET.
EDIT
I noticed one apparently strange thing in the code of ProcessB
. This code
using (MemoryMappedViewStream stream = mmf.CreateViewStream(1, 0))
creates a view from the first byte, but the strings in .NET
are 2 bytes. I think it should be enough to you to make that 1->2
become 2. So the offset of the ProcessB
view from the start of the mapped file will be after already inserted "1" string from ProcessA
.
In your case seems that you overlap them.
Hope this helps.