进程间通讯
为了实现2个进程间的内存共享,我采用了如下方式
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO.MemoryMappedFiles;
using System.IO;
namespace MsgTransferService
{
class ShareMemory
{
private static string _myMutex = "MyMutex";
private static string _myMemoryMap = "MyMemoryMap";
public ShareMemory()
{
}
public void BeginShareMemory()
{
new ShareMemory().Run();
}
public void Run()
{
ThreadPool.QueueUserWorkItem(this.Observer);
}
void Observer(object state)
{
int lastOffset = sizeof(int);
while (true)
{
notifyEvent.WaitOne();
if (GetMsgBytes(ref lastOffset) == false)
{
Thread.Sleep(50);
}
}
}
public void PutBytes(Byte[] msgBytes)
{
try
{
mutex.WaitOne();
using (MemoryMappedViewAccessor accessor = memMap.CreateViewAccessor())
{
int offset = accessor.ReadInt32(0);
offset = Math.Max(sizeof(int), offset);
accessor.Write(offset, (int)msgBytes.Length);
offset += sizeof(int);
accessor.WriteArray<byte>(offset, msgBytes, 0, msgBytes.Length);
offset += msgBytes.Length;
accessor.Write(0, offset);
}
}
finally
{
mutex.ReleaseMutex();
}
notifyEvent.Set();
Thread.Sleep(100);
notifyEvent.Reset();
}
bool GetMsgBytes(ref int lastOffset)
{
try
{
mutex.WaitOne();
using (MemoryMappedViewAccessor accessor = memMap.CreateViewAccessor())
{
int newOffset = accessor.ReadInt32(0);
if (newOffset <= lastOffset) return false;
for (int offset = lastOffset; offset < newOffset; )
{
int stringLength = accessor.ReadInt32(offset); offset += sizeof(int);
byte[] bytes = new byte[stringLength];
accessor.ReadArray<byte>(offset, bytes, 0, bytes.Length);
offset += stringLength;
DisplayMsg(bytes);
}
lastOffset = newOffset;
}
}
catch(Exception ex)
{
StreamWriter sw = new StreamWriter(@"D:\msg.log", true, System.Text.Encoding.GetEncoding("gb2312"));
sw.WriteLine(DateTime.Now + " 接收到包:" + ex.ToString());
sw.Close();
sw.Dispose();
}
finally
{
mutex.ReleaseMutex();
}
return true;
}
void DisplayMsg(byte[] msgBytes)
{
}
Mutex mutex = new Mutex(true, _myMutex);
MemoryMappedFile memMap = MemoryMappedFile.CreateOrOpen(_myMemoryMap, 1024 * 1024);
EventWaitHandle notifyEvent = new EventWaitHandle(false, EventResetMode.ManualReset, "MyNotifyEvent");
}
}
[解决办法]
用remote也行哦
[解决办法]