1

I need to work with a single file (read and write) from DIFFERENT processes. Since there is a competition between processes, it is necessary to block the file. Currently recording is implemented as follows:

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

Is there a proper solution to my problem?

Shajo
  • 873
  • 2
  • 11
  • 22
qwerty666
  • 13
  • 3

1 Answers1

0

You can use a Named Mutex to share a lock between processes:

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();
}
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
  • If all the processes that access the file, will use mutex, then I'll be able to do so: http://pastebin.com/9MhaSzTs Will it work? – qwerty666 Sep 07 '14 at 15:28
  • Yes, that is the point of a shared mutex. When creating it by name, and will return the already constructed mutex. – Yuval Itzchakov Sep 07 '14 at 15:30