当我执行下面的代码时,我得到了一个常见的异常
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.");
}
}
}