Multi processes read&write one file

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).

Leave a Comment