if (Directory.Exists(dir))
Directory.Delete(dir, true);
上面的代码检查目录是否存在,如果存在则删除它。在存在检查和删除之间,可能会添加或删除目录。
除了调用 .Delete 并丢弃异常之外,是否有适当的方法来防止这种竞争条件?
编辑:
避免与异常处理竞争条件的原因是因为 exceptions should not be used for control flow.
一个理想的解决方案是某种文件系统锁?
最佳答案
如果想要的最终结果是确保目录 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.
}
关于.net - 如何避免 File.Exists/File.Delete 或 Directory.Exists/Directory.Delete 中的竞争,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28241469/