来自不同进程的对文件的原子操作
本文关键字:原子操作 文件 进程 | 更新日期: 2023-09-27 18:21:03
我需要处理来自不同进程的单个文件(读写)。由于进程之间存在竞争,因此有必要阻止该文件。目前的记录方式如下:
const int MAX_RETRY = 50;
const int DELAY_MS = 200;
bool Success = false;
int Retry = 0;
while (!Success && Retry < MAX_RETRY)
{
try
{
using (StreamWriter Wr = new StreamWriter(ConfPath))
{
Wr.WriteLine("My content");
}
}
catch (IOException)
{
Thread.Sleep(DELAY_MS);
Retry++;
}
}
我的问题有合适的解决办法吗?
您可以使用命名互斥在进程之间共享锁:
const int MAX_RETRY = 50;
const int DELAY_MS = 200;
bool Success = false;
int Retry = 0;
// Will return an existing mutex if one with the same name already exists
Mutex mutex = new Mutex(false, "MutexName");
mutex.WaitOne();
try
{
while (!Success && Retry < MAX_RETRY)
{
using (StreamWriter Wr = new StreamWriter(ConfPath))
{
Wr.WriteLine("My content");
}
Success = true;
}
}
catch (IOException)
{
Thread.Sleep(DELAY_MS);
Retry++;
}
finally
{
mutex.ReleaseMutex();
}