Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will a C# MemoryMappedFile expand?

I am using a MemoryMappedFile to exchange data between two processes. So I created/opened the file like this in both processes:

MemoryMappedFile m_MemoryMappedFile = MemoryMappedFile.CreateOrOpen("Demo", 8);

The file access itself is protected with a global mutex in both processes. Now when I write data to the file which is bigger than the defined length of 8 bytes I do NOT get an exception.

var random = new Random();
var testData = new byte[55];
random.NextBytes(testData);
using (var contentAccessor = m_MemoryMappedFile.CreateViewStream())
{
    contentAccessor.Write(testData, 0, testData.Length);
}

So perhaps I am getting something wrong here, but I thought if I create a non persistent memory mapped file with a specified capacity (in my case 8 bytes) it is not allowed to write more data than 8 bytes? Or do I corrupt the memory with my call above? Any explanation would be great?

like image 495
Franz Gsell Avatar asked Oct 11 '25 14:10

Franz Gsell


1 Answers

This is specifically mentioned in the documentation for CreateViewStream():

To create a complete view of the memory-mapped file, specify 0 (zero) for the size parameter. If you do this, the size of the view might be larger than the size of the source file on disk. This is because views are provided in units of system pages, and the size of the view is rounded up to the next system page size.

It is indeed rounded up to the page size. Best thing to do is to use the method overload that lets you set the view size:

using (var contentAccessor = m_MemoryMappedFile.CreateViewStream(0, 8))
{
    contentAccessor.Write(testData, 0, testData.Length);
}
like image 192
Hans Passant Avatar answered Oct 14 '25 06:10

Hans Passant