日期:2014-05-17 浏览次数:21130 次
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);
&nbs