在.NET中有這樣一個類MemoryMappedFile,顧名思義:內存文件映射.
這個類可以很方便的將硬盤中的物理文件,映射到內存中,操作文件時,就可以直接從內存中讀取寫入了。省去了磁盤轉入內存,內存轉磁盤的操作時間,效率當然也是更高。
這適合用於大文件頻繁的讀寫,效果比較顯著。
除了從已有的物理文件加載數據源(MemoryMappedFile.CreateFromFile),也支持在內存中直接創建數據(MemoryMappedFile.CreateOrOpen),
直接在內存中創建數據並保留.並且這段內存是特殊的,是可以共享的,即:共享內存。
在同一台PC,運行的軟件(進程),系統都會給其分配一段內存供其調度運行.每個進程獨占這段內存,互不干擾。那么共享內存,就好比一個公共區域,
每個進程都可以申請,使用。MemoryMappedFile正是具有這個特性,所以可以實現進程間的相互通信.
在同一PC種,利用它實現進程間通信,是非常方便且高效的!
這里自己做了個簡單DEMO,旨意闡述MemoryMappedFile具有實現進程間通信的功能.
完整代碼如下:

1 using System; 2 using System.Collections; 3 using System.Collections.Generic; 4 using System.Collections.Specialized; 5 using System.Linq; 6 using System.Net; 7 using System.Net.Sockets; 8 using System.Text; 9 using System.Threading; 10 using System.Threading.Tasks; 11 using System.Net.NetworkInformation; 12 using System.IO; 13 using System.IO.Compression; 14 using ICSharpCode.SharpZipLib.Zip; 15 using System.IO.MemoryMappedFiles; 16 using System.Runtime.InteropServices; 17 18 namespace ConsoleApplication3 19 { 20 class Program 21 { 22 static void Main(string[] args) 23 { 24 Console.WriteLine("注: w:寫 r:讀"); 25 while (true) 26 { 27 string ac = Console.ReadLine(); 28 29 if (ac == "w") 30 { 31 Console.WriteLine("請輸入存入內容:"); 32 string content = Console.ReadLine(); 33 if (!string.IsNullOrEmpty(content)) 34 { 35 WriteMMF("mmf001", content); 36 } 37 else { 38 Console.WriteLine("存入內容不能為空!"); 39 } 40 } 41 else if (ac == "r") 42 { 43 ReadMMF("mmf001"); 44 } 45 else { 46 47 Console.WriteLine("注: w:寫 r:讀"); 48 } 49 } 50 51 } 52 /// <summary> 53 /// 寫入映射文件 54 /// </summary> 55 /// <param name="mapname"></param> 56 /// <param name="content"></param> 57 static void WriteMMF(string mapname,string content) { 58 59 MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapname,1000, MemoryMappedFileAccess.ReadWrite); 60 if (!string.IsNullOrEmpty(content)) 61 { 62 using (var mmfStream = mmf.CreateViewStream()) 63 { 64 using (var sw = new StreamWriter(mmfStream)) 65 { 66 sw.Write(content.Trim()); 67 } 68 } 69 70 Console.WriteLine("保存成功!"); 71 } 72 } 73 74 /// <summary> 75 /// 讀取映射文件 76 /// </summary> 77 /// <param name="mapname"></param> 78 static void ReadMMF(string mapname) 79 { 80 MemoryMappedFile mmf = MemoryMappedFile.OpenExisting(mapname); 81 using (var mmfStream = mmf.CreateViewStream(0,1000, MemoryMappedFileAccess.ReadWrite)) 82 { 83 byte[] buffer = new byte[128]; 84 int nLength = 0; 85 StringBuilder sb = new StringBuilder(); 86 do 87 { 88 nLength = mmfStream.Read(buffer, 0, 128); 89 sb.AppendLine(System.Text.ASCIIEncoding.Default.GetString(buffer)); 90 91 } while (nLength > 0); 92 93 Console.WriteLine("讀取內容:" + sb.ToString().Replace("\0", null).TrimEnd()); 94 } 95 Console.WriteLine("讀取成功!"); 96 } 97 98 } 99 100 101 102 }
測試效果圖: