Multi processes read&write one file

后端 未结 5 1324
暗喜
暗喜 2020-11-30 02:26

I have a txt file ABC.txt which will be read and wrote by multi processes. So when one process is reading from or writing to file ABC.txt, file ABC.txt must be locked so tha

5条回答
  •  悲哀的现实
    2020-11-30 03:07

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

提交回复
热议问题