//Shared Memory
using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen("sharedmem",500))
{
object obj = new Object();
ManualResetEvent myevent = new ManualResetEvent(false);
//写入线程每500ms发送一个消息,并发出一次event
Thread th_writer = new Thread(() =>
{
int i = 0;
while (true)
{
using (MemoryMappedViewStream buff = mmf.CreateViewStream())
{
byte[] buffer = Encoding.UTF8.GetBytes($"hello reader!{i}");
lock (obj)
{
buff.Write(buffer, 0, buffer.Length);
$"msg sent".Dump();
myevent.Set();
}
i++;
Thread.Sleep(500);
}
}
});
//读取线程循环等待event后读取消息
Thread th_reader = new Thread(() =>
{
while (true)
{
using (MemoryMappedViewStream stream = mmf.CreateViewStream())
{
myevent.WaitOne();
byte[] buffer = new byte[1000];
string message = "";
lock (obj)
{
stream.Read(buffer, 0, buffer.Length);
message = Encoding.UTF8.GetString(buffer).Trim('\0');
}
$"receive msg:{message}".Dump();
myevent.Reset();
Thread.Sleep(5);
}
}
});
th_reader.Start();
th_writer.Start();
while (true)
{
await Task.Delay(1000);
}
}
标签:Thread,C#,通信,buffer,myevent,th,new,message,共享内存
From: https://www.cnblogs.com/senya8030/p/18051601