gpt4 book ai didi

c# - MemoryMappedFile 流的死锁

转载 作者:太空宇宙 更新时间:2023-11-03 17:04:13 34 4
gpt4 key购买 nike

我在执行 MemoryMappedFile 流式传输时遇到了一个小问题。我有 2 个项目,一个用于发送字节,另一个用于读取字节。在这两个进程之间应该有一个 2 秒的 sleep 定时器。

我已经实现了所有这些,但是当软件尝试进行读取时,它似乎遇到了死锁。这两个过程的代码如下。

谁能帮我找出问题所在?

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();

}
}
}

关于c# - MemoryMappedFile 流的死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8847381/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com