代码之家  ›  专栏  ›  技术社区  ›  Daniel Dyson

进程无法访问该文件,因为另一个进程正在使用它

  •  2
  • Daniel Dyson  · 技术社区  · 15 年前

    当我执行下面的代码时,我得到了一个常见的异常 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.");
                }
            }
        }
    
    2 回复  |  直到 15 年前
        1
  •  3
  •   kbrimington    15 年前

    如果有多个线程试图访问同一个文件,请考虑使用锁定机制。最简单的形式可以是:

    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
  •  3
  •   Oliver    15 年前

    你可以设置一个 FileShare File.Open 命令式

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

    但我认为,如果有多个线程试图写入一个文件,最干净的方法就是将所有这些消息放入一个文件中 Queue<T> 并有一个附加线程将队列的所有元素写入文件。