【问题标题】:atomic operations on a file from different processes来自不同进程的文件的原子操作
【发布时间】:2014-09-07 14:50:16
【问题描述】:

我需要处理来自不同进程的单个文件(读取和写入)。由于进程之间存在竞争,因此需要阻塞文件。目前录制实现如下:

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

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

【问题讨论】:

标签: c# multithreading file locking atomic


【解决方案1】:

您可以使用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();
}

【讨论】:

  • 如果所有访问该文件的进程都使用互斥锁,那我就可以这样做了:pastebin.com/9MhaSzTs 可以吗?
  • 是的,这就是共享互斥锁的意义所在。按名称创建时,会返回已经构建好的互斥体。
猜你喜欢
  • 2015-02-26
  • 2020-01-08
  • 2020-10-25
  • 1970-01-01
  • 1970-01-01
  • 2020-02-24
  • 1970-01-01
  • 1970-01-01
  • 2017-03-25
相关资源
最近更新 更多