Multi processes read&write one file

后端 未结 5 1327
暗喜
暗喜 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 02:59

    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

提交回复
热议问题