Reputation: 8404
I want to pass some information between 2 processes. Basically, it is a number of strings, and since I dont want to restrict the strings in any way (I could pass it through command line since I spawn the 2nd process) I thought to give shared memory a go. (Named pipes seem a bit more complicated from samples.)
So I simply copy/pasted the sample (actually, sample used binary streams, I use text streams) code and use breakpoints right now for synchronization.
Sender code
using (System.IO.MemoryMappedFiles.MemoryMappedFile mmf = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateNew("mymappedfile", 10000))
{
using (System.IO.MemoryMappedFiles.MemoryMappedViewStream stream = mmf.CreateViewStream())
{
StreamWriter w = new StreamWriter(stream);
w.WriteLine("Hello!");
w.WriteLine("Andreas!");
w.WriteLine("Teststring #+#\"\" ,,a8&&");
//BinaryWriter writer = new BinaryWriter(stream);
w.Flush();
}
}
Receiver code
using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("mymappedfile"))
{
using (MemoryMappedViewStream stream = mmf.CreateViewStream(1, 0))
{
StreamReader r = new StreamReader(stream);
string str;
while ((str = r.ReadLine()) != null)
{
System.Diagnostics.Debug.WriteLine(str);
}
}
}
Output
ello!
Andreas!
Teststring #+#"" ,,a8&&
There is the H of Hello! missing.
Should I use BinaryStreams instead or what could be the issue here?
Upvotes: 1
Views: 1451
Reputation: 11926
mmf.CreateViewStream(1/* selects first byte */, 0)
to
mmf.CreateViewStream(0/* selects zeroth byte*/, 0)
Here it is: http://msdn.microsoft.com/en-us/library/dd267553(v=vs.110).aspx
Like this:
public MemoryMappedViewStream CreateViewStream(
long offset, // you have set it to 1 but should start from 0
long size
)
Upvotes: 2