如何避免 File.Exists/File.Delete 或 Directory.Exists/Directory.Delete 中的竞争

Jos*_*nox 4 .net file-io

if (Directory.Exists(dir))
    Directory.Delete(dir, true);
Run Code Online (Sandbox Code Playgroud)

上面的代码检查该目录是否存在,如果存在,则将其删除。在存在检查和删除之间,目录有可能被添加或删除。

除了调用 .Delete 并丢弃异常之外,是否有适当的方法来防止这种竞争条件?

编辑:

避免与异常处理竞争的原因是因为异常不应该用于控制流。

理想的解决方案是某种文件系统锁?

das*_*ght 5

如果期望的最终结果是确保该目录dir不存在,无论它是否存在,那么您应该调用Directory.Delete 并捕获它可能抛出的任何异常,而不必费心检查该目录是否存在。然后你应该检查该目录是否存在,看看你是否可以继续,或者你的操作是否因其他原因失败:

try {
    Directory.Delete(dir, true);
} catch {
    // Ignore any exceptions
}
if (Directory.Exists(dir)) {
    // The above has failed to delete the directory.
    // This is the situation to which your program probably wants to react.
}
Run Code Online (Sandbox Code Playgroud)