Using shared memory for inter process communication in .NET

dapper

We can use a not persisted memory mapped file

Server side


public static void WriteMappedFile(string name, string content)
{
	
	SecurityIdentifier everyone = new (WellKnownSidType.WorldSid, null);
            
	var security = new MemoryMappedFileSecurity();
	security.AddAccessRule(new AccessRule<MemoryMappedFileRights>(
		everyone, 
		content.Length,
		MemoryMappedFileRights.FullControl,
		AccessControlType.Allow
	));

	MemoryMappedFile memoryMappedFile = MemoryMappedFile.CreateOrOpen($"Global\\{name}",
         MemoryMappedFileAccess.ReadWrite);

	memoryMappedFile.SetAccessControl(security);

	using (MemoryMappedViewStream viewStream = memoryMappedFile.CreateViewStream())
	using (StreamWriter streamWriter = new (viewStream))
	{
		streamWriter.WriteLine(content);
	}
}

Client Side


public static string ReadMappedFile(string name) 
{
	MemoryMappedFile memoryMappedFile = MemoryMappedFile
    	.OpenExisting($"Global\\{name}", MemoryMappedFileRights.Read);

	if (memoryMappedFile == null) 
	{
		return false;
	}
            
	MemoryMappedViewStream viewStream = memoryMappedFile
    	.CreateViewStream(0, 0, MemoryMappedFileAccess.Read);
	StreamReader streamReader = new StreamReader(viewStream);
	string content = streamReader.ReadLine();
	return content;
}

Note! Without using the "Global\" prefix, the memory mapped file won't be available to processes running under a different security context.

Post a Comment

Previous Post Next Post