簡體   English   中英

該進程無法訪問該文件,因為它正在被另一個進程使用

[英]The process cannot access the file because it is being used by another process

當我執行以下代碼時,我得到一個常見的異常: 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.");
            }
        }
    }

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

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

作為替代方案,請考慮:

File.AppendText(text);

您可以使用此File.Open命令將FileShare設置為允許多重訪問

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

但是我認為,如果您有多個試圖寫入一個文件的線程,最干凈的方法是將所有這些消息放入Queue<T>並有一個額外的線程將隊列的所有元素寫入文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM