对来自不同进程的文件的原子操作

时间:2014-09-07 14:50:17

标签: c# multithreading file locking atomic

我需要使用来自DIFFERENT进程的单个文件(读写)。由于进程之间存在竞争,因此必须阻止该文件。目前录制如下:

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++;
    }
}

我的问题有适当的解决方案吗?

1 个答案:

答案 0 :(得分:0)

您可以使用Named Mutex在进程之间共享锁定:

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