C# 不同进程对文件的原子操作
我需要处理从不同进程读取和写入的单个文件。由于进程之间存在竞争,因此有必要阻止该文件。目前的录制方式如下:C# 不同进程对文件的原子操作,c#,multithreading,file,locking,atomic,C#,Multithreading,File,Locking,Atomic,我需要处理从不同进程读取和写入的单个文件。由于进程之间存在竞争,因此有必要阻止该文件。目前的录制方式如下: 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 Strea
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();
}
这两个进程都执行读写操作吗?这两个进程都可以读写文件。您可以使用互斥。如果所有访问该文件的进程都将使用互斥,那么我就可以这样做:它会工作吗?是的,这就是共享互斥的要点。按名称创建时,将返回已构造的互斥体。