2010-08-11 64 views
2

當我執行下面的代碼時,出現普通異常The process cannot access the file *filePath* because it is being used by another process進程無法訪問該文件,因爲它正在被另一個進程使用

允許此線程等待它可以安全地訪問此文件的最有效方法是什麼?

假設:

  • 文件剛剛被我創建的,所以這是不可能的另一個應用程序正在訪問它。
  • 來自我的應用程序的多個線程可能試圖運行此代碼以將文本附加到該文件。

using (var fs = File.Open(filePath, FileMode.Append)) //Exception here 
{ 
    using (var sw = new StreamWriter(fs)) 
    { 
     sw.WriteLine(text); 
    } 
} 

到目前爲止,我想出了是下面的最好的。這樣做有什麼缺點嗎?

private static void WriteToFile(string filePath, string text, int retries) 
    { 
     const int maxRetries = 10; 
     try 
     { 
      using (var fs = File.Open(filePath, FileMode.Append)) 
      { 
       using (var sw = new StreamWriter(fs)) 
       { 
        sw.WriteLine(text); 
       } 
      } 
     } 
     catch (IOException) 
     { 
      if (retries < maxRetries) 
      { 
       Thread.Sleep(1); 
       WriteToFile(filePath, text, retries + 1); 
      } 
      else 
      { 
       throw new Exception("Max retries reached."); 
      } 
     } 
    } 

回答

3

如果您有多個線程試圖訪問同一個文件,請考慮使用鎖定機制。最簡單的形式可以是:

lock(someSharedObject) 
{ 
    using (var fs = File.Open(filePath, FileMode.Append)) //Exception here 
    { 
     using (var sw = new StreamWriter(fs)) 
     { 
      sw.WriteLine(text); 
     } 
    } 
} 

作爲替代方案,可以考慮:

File.AppendText(text); 
2

您可以設置FileShare允許像

File.Open(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite) 

與此File.Open命令多址但我認爲如果你有多個線程試圖寫入一個文件,最簡潔的方法是將所有這些消息放入一個Queue<T>和h一個額外的線程將隊列的所有元素寫入文件。

+0

在我的情況下,這仍然拋出相同的異常。我想念什麼? – 2015-07-27 13:27:33

+0

@MauroBilotti:你確定,你的過程是唯一一個訪問文件? – Oliver 2015-07-27 13:29:48

+0

奧利弗,它的工作原理是,我必須在'閱讀'模式下更改文件訪問權限,因爲我是以這種方式打開它。謝謝!我會鼓勵你 – 2015-07-27 13:44:04

相關問題