Multi processes read&write one file

后端 未结 5 1306
暗喜
暗喜 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:09

    C# has a built in lock and you can use it by creating a static object which all threads have acess to:

    private static object lockObject {get;set;}
    
    public static object LockObject {get{return lockObject ?? lockObject = new object();}}
    
    
    void YourMethod()
    {
       lock(LockObject)  // all other threads will wait for y
       {
          using(var lockFileStream = File.Open("Lock.txt", FileMode.Open, FileAccess.Read, FileShare.None))
          {
             //Do what you need with the file.  
          }
    
       }
    }
    

    This creates a Thread Safe approach to your problem.

提交回复
热议问题