首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >来自不同进程的文件的原子操作

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

Stack Overflow用户
提问于 2014-09-07 14:50:16
回答 1查看 67关注 0票数 1

我需要处理来自不同进程的单个文件(读和写)。由于进程之间存在竞争,因此有必要阻止文件。目前正在按以下方式进行记录:

代码语言:javascript
复制
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++;
    }
}

我的问题有适当的解决办法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-09-07 15:02:15

您可以使用名为Mutex在进程之间共享锁:

代码语言:javascript
复制
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();
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25711456

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档