我需要处理来自不同进程的单个文件(读和写)。由于进程之间存在竞争,因此有必要阻止文件。目前正在按以下方式进行记录:
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++;
}
}我的问题有适当的解决办法吗?
发布于 2014-09-07 15:02:15
您可以使用名为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();
}https://stackoverflow.com/questions/25711456
复制相似问题