我有一个代理进程,许多客户端应用程序将使用 .Net 远程处理连接到该进程。我想通过使用一些引用计数方案来管理这个代理的存在。为此,我想我会使用一个小的内存映射文件,我将在其中存储一个键值(字符串-整数)对,它看起来像这样:
ref_count 2
但是,我想不时更新 ref_count 值,但这样做时遇到问题。这是我的代码:
using System;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Threading;
class Program
{
static void Main(string[] args)
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("testmap", 100))
{
bool mutexCreated;
Mutex mutex = new Mutex(true, "testmapmutex", out mutexCreated);
using (MemoryMappedViewStream stream = mmf.CreateViewStream())
{
BinaryWriter writer = new BinaryWriter(stream);
writer.Write("count:");
writer.Write(3);
}
mutex.ReleaseMutex();
mutex.WaitOne();
using (MemoryMappedViewStream stream = mmf.CreateViewStream())
{
BinaryReader reader = new BinaryReader(stream);
BinaryWriter writer = new BinaryWriter(stream);
Console.WriteLine("String value is: {0}", reader.ReadString());
Console.WriteLine("UInt32 value is: {0}", reader.ReadUInt32());
// Update mmf data
writer.Write("count:");
writer.Write(30);
// empty string where "count" was expected
Console.WriteLine("String value is: {0}", reader.ReadString());
// 0 where 30 was expected
Console.WriteLine("UInt32 value is: {0}", reader.ReadUInt32());
}
mutex.ReleaseMutex();
}
}
}
所以,我的问题是,更新我的引用计数的最佳方法是什么,以及为什么我的第二次写入在上面的代码示例中不起作用?
谢谢,