如果您绝对必须这样做,并且您无法控制正在使用该文件的应用程序,那么您的代码几乎就在那里。
它只需要稍微健壮一点:
public static bool TryWriteText(string path, string text, TimeSpan timeout)
{
Contract.Requires(path != null); // Or replace with: if (path == null) throw new ArgumentNullException("path");
Contract.Requires(text != null); // Or replace with: if (text == null) throw new ArgumentNullException("text");
Stopwatch stopwatch = Stopwatch.StartNew();
while (stopwatch.Elapsed < timeout)
{
try
{
File.WriteAllText(path, text);
return true;
}
catch (IOException){} // Ignore IOExceptions until we time out, then return false.
Thread.Sleep(100); // 100ms is rather short - it could easily be 1000 I think.
} // Perhaps this should be passed in as a parameter.
return false;
}
在超时时重新抛出最后一个的替代版本IOException
(这可以说更好,因为您不隐藏所有异常):
public static void TryWriteText(string path, string text, TimeSpan timeout)
{
Contract.Requires(path != null); // Or replace with: if (path == null) throw new ArgumentNullException("path");
Contract.Requires(text != null); // Or replace with: if (text == null) throw new ArgumentNullException("text");
Stopwatch stopwatch = Stopwatch.StartNew();
while (true)
{
try
{
File.WriteAllText(path, text);
}
catch (IOException)
{
if (stopwatch.Elapsed > timeout)
throw;
}
Thread.Sleep(100);
}
}
但是您应该只将此类代码用作最后的手段。