Multi processes read&write one file

Solution 1:

C#'s named EventWaitHandle is the way to go here. Create an instance of wait handle in every process which wants to use that file and give it a name which is shared by all such processes.

EventWaitHandle waitHandle = new EventWaitHandle(true, EventResetMode.AutoReset, "SHARED_BY_ALL_PROCESSES");

Then when accessing the file wait on waitHandle and when finished processing file, set it so the next process in the queue may access it.

waitHandle.WaitOne();
/* process file*/
waitHandle.Set();

When you name an event wait handle then that name is shared across all processes in the operating system. Therefore in order to avoid possibility of collisions, use a guid for name ("SHARED_BY_ALL_PROCESSES" above).

Solution 2:

A mutex in C# may be shared across multiple processes. Here is an example for multiple processes writing to a single file:

using (var mutex = new Mutex(false, "Strand www.jakemdrew.com"))
{
    mutex.WaitOne();
    File.AppendAllText(outputFilePath,theFileText);
    mutex.ReleaseMutex();
}

You need to make sure that the mutex is given a unique name that will be shared across the entire system.

Additional reading here:

http://www.albahari.com/threading/part2.aspx#_Mutex