MemoryMappedFile流的死锁
本文关键字:死锁 MemoryMappedFile | 更新日期: 2023-09-27 18:20:07
我在执行MemoryMappedFile流时遇到一个小问题。我有两个项目,一个用于发送字节,另一个用于读取字节。在这两个进程之间应该有一个2秒的睡眠定时器。
我已经实现了所有这些,但当软件尝试读取时,它似乎遇到了死锁。这两个过程的代码如下。
有人能帮我找到问题吗?
namespace ProcesComunication
{
class Program
{
static void Main(string[] args)
{
MemoryMappedFile mmf = MemoryMappedFile.CreateNew("AAB", 1024);
MemoryMappedViewStream mStream = mmf.CreateViewStream();
BinaryWriter bw = new BinaryWriter(mStream);
Mutex mx = new Mutex(true, "sync");
while (true)
{
Thread.Sleep(2000);
Console.WriteLine("TEST");
bw.Write(DateTime.Now.ToString());
mx.ReleaseMutex();
}
bw.Close();
mStream.Close();
}
}
}
namespace ProcesRead
{
class Program
{
static void Main(string[] args)
{
MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("AAB");
MemoryMappedViewStream mStream = mmf.CreateViewStream();
BinaryReader br = new BinaryReader(mStream);
Mutex mx = Mutex.OpenExisting("sync");
while (true)
{
mx.WaitOne();
Console.Write(br.ReadString());
mx.ReleaseMutex();
}
br.Close();
mStream.Close();
}
}
}
我尝试并找到了简单的解决方案,下面是一段代码:感谢所有贡献者的回答。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using System.IO.MemoryMappedFiles;
namespace ProcesComunication
{
class Program
{
static void Main(string[] args)
{
MemoryMappedFile mmf = MemoryMappedFile.CreateNew("AAB", 1024);
MemoryMappedViewStream mStream = mmf.CreateViewStream();
BinaryWriter bw = new BinaryWriter(mStream);
Mutex mx = new Mutex(true, "sync");
while (true)
{
mx.WaitOne();
Thread.Sleep(2000);
var random = new Random();
var nextValue = random.Next().ToString();
Console.WriteLine(nextValue);
bw.Write(nextValue);
mx.ReleaseMutex();
}
bw.Close();
mStream.Close();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using System.IO.MemoryMappedFiles;
namespace ProcesRead
{
class Program
{
static void Main(string[] args)
{
MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("AAB");
MemoryMappedViewStream mStream = mmf.CreateViewStream();
BinaryReader br = new BinaryReader(mStream);
Mutex emx = Mutex.OpenExisting("sync");
while (true)
{
Console.WriteLine(br.ReadString());
emx.WaitOne(2000);
}
br.Close();
mStream.Close();
}
}
}
不需要使用同步对象(Mutex)。MemoryMappedFile是进程之间的线程安全。不要使用互斥。并控制读卡器对其进行数据读取。