1 /// <summary>
2 /// 进程间通讯,共享映射文件
3 /// </summary>
4 public class MappingHelper
5 {
6 long capacity = 1024 * 1024;
7 public MemoryMappedFile file;
8
9 public MappingHelper()
10 {
11 }
12
13 public MappingHelper(string fileName,string mapName)
14 {
15 file = MemoryMappedFile.CreateFromFile(fileName,FileMode.OpenOrCreate,mapName,capacity);
16 }
17
18 /// <summary>
19 /// 将消息写入共享映射文件
20 /// </summary>
21 /// <param name="msg">消息内容</param>
22 public void WriteString(string msg)
23 {
24 using (var stream = file.CreateViewStream())
25 {
26 using (var writer = new BinaryWriter(stream))
27 {
28 writer.Write(msg);
29 }
30 }
31 }
32 /// <summary>
33 /// 从共享映射文件中读取消息
34 /// </summary>
35 /// <returns></returns>
36 public string ReadString()
37 {
38 using (var stream = file.CreateViewStream())
39 {
40 using (var reader = new BinaryReader(stream))
41 {
42 List<byte> bytes = new List<byte>();
43 byte[] temp = new byte[1024];
44 while (true)
45 {
46 int readCount = reader.Read(temp, 0, temp.Length);
47 if (readCount == 0)
48 {
49 break;
50 }
51 for (int i = 0; i < readCount; i++)
52 {
53 bytes.Add(temp);
54 }
55 }
56 if (bytes.Count > 0)
57 {
58 return Encoding.Default.GetString(bytes.ToArray()).Replace("\0", "");
59 }
60 else
61 {
62 return null;
63 }
64 }
65 }
66 }
67 }