MemoryMappedFile
一、MemoryMappedFileService
using System; using System.IO; using System.IO.MemoryMappedFiles; using System.Text; namespace MemoryMappedFileService { class Program { static void Main(string[] args) { MemoryMappedFile memoryAccessor = MemoryMappedFile.CreateNew("ProcessCommunicationAccessor", 500, MemoryMappedFileAccess.ReadWrite); using (var accessor = memoryAccessor.CreateViewAccessor())//获取映射文件对象的存储器 { var buffer = Encoding.UTF8.GetBytes("Accessor"); accessor.WriteArray(0, buffer, 0, buffer.Length);//将给定的值写入此视图中 Console.WriteLine(Environment.NewLine + "Accessor Send Val:Accessor"); } MemoryMappedFile memoryStream = MemoryMappedFile.CreateNew("ProcessCommunicationStream", 500, MemoryMappedFileAccess.ReadWrite);//创建流的映射文件对象 using (var stream = memoryStream.CreateViewStream())//获取映射文件的流 { var buffer = Encoding.UTF8.GetBytes("Stream"); stream.Write(buffer, 0, buffer.Length);//将给定的值写入此内存流中 Console.WriteLine(Environment.NewLine + "Accessor Send Val:Stream"); } Console.ReadLine(); } } }
二、MemoryMappedFileClient
using System; using System.IO; using System.IO.MemoryMappedFiles; using System.Text; namespace MemoryMappedFileClient { class Program { static void Main(string[] args) { System.Threading.Thread.Sleep(1000); MemoryMappedFile memoryAccessor = MemoryMappedFile.OpenExisting("ProcessCommunicationAccessor");//获取服务端定义的ProcessCommunicationAccessor名称的内存映射文件然后调用ReadArray方法读取到服务端写入的数据 using (var accessor = memoryAccessor.CreateViewAccessor()) { var buffer = new byte[999]; var read = accessor.ReadArray(0, buffer, 0, buffer.Length); var str = Encoding.UTF8.GetString(buffer); Console.WriteLine(Environment.NewLine + "Accessor Read Val:" + str.ToString()); } MemoryMappedFile memoryStream = MemoryMappedFile.OpenExisting("ProcessCommunicationStream");//获取服务端定义的ProcessCommunicationStream名称的内存映射文件然后调用ReadToEnd方法读取到服务端写入的数据 using (var stream = memoryStream.CreateViewStream()) { using (var reader = new StreamReader(stream)) { var str = reader.ReadToEnd(); Console.WriteLine(Environment.NewLine + "Stream Read Val:" + str + "\r\n"); } } Console.ReadLine(); } } }