读书人

进程间通讯,该如何处理

发布时间: 2013-11-27 21:59:41 作者: rapoo

进程间通讯
为了实现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");
}
}


现在有2个问题困扰了我好几天:
1,如果我在应用程序端(A)调用new ShareMemory().PutBytes(msgBytes)往共享内存中写入数据,在另外的一个控制台程序(C)上是能正常的获得这个数据的,如果我用C往内存中写数据,A却获取不到,也检测不到内存改变的通知;
2,发送端还是A,这个时候把C换成Windows service(S),S获取不到A往内存中共享的数据,A也获取不到S往内存中共享的数据。

求高人指点。


[解决办法]
用remote也行哦
[解决办法]

引用:
用remote也行哦
您这头像是拉登吧

[解决办法]
引用:
Quote: 引用:

用remote也行哦
您这头像是拉登吧

不是拉登好吧,拉登哪有这么帅。
这是古巴革命英雄切格瓦拉,传奇人物啊

读书人网 >C#

热点推荐