c# - Directory.CreateDirectory 是异步的还是什么?

标签 c# .net

我有以下代码来为我生成的文件准备一个文件夹:

if (Directory.Exists(outputDir))
{
    Directory.Delete(outputDir, true);
}
Directory.CreateDirectory(outputDir);

当我正常运行它时,恰好每隔一秒它就工作一次,而另一次它抛出一个 DirectoryNotFoundException,在线:

File.WriteAllLines(filePath, CreateRows(TestLineCount, TestSampleCount));

找不到路径的一部分 'C:\Dev\Android\Projects...filePath 中的最后一个文件夹丢失了,因为我删除了它,但后来我又创建了它,所以它应该一直在那里。当我在 Directory.CreateDirectory(outputDir); 行上放置一个断点时,有一个小的延迟,应用程序每次都能正常工作。如果我引入自动延迟,即:

Directory.CreateDirectory(outputDir);
Thread.Sleep(500);

它也每次都有效。当然所有这些调用都应该阻塞直到完成,所以 outputDir 总是在那里?

最佳答案

我认为它不是异步的,但是当你这样调用它时

Directory.CreateDirectory(outputDir); //App is trying to create directory
//successfully created but depends on OS how fast OS commits the changes

Thread.Sleep(500); //assuming physically creation on Hard and its availability in OS took less then 500ms then this wait works or else we have to wait more

//this delay is actually totally non generic since the time differs OS to OS


 // its just a rough guess that changes will be committed within 500ms

if(!Directory.Exists(outputDir))
  //if still not exists Your OS que is being processed very slow due to 
  //some not known reason! so you have to wait more then 500ms

关于c# - Directory.CreateDirectory 是异步的还是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39303525/

相关文章:

c# - 为什么 Blazor UI 组件在删除事件后没有更新?

c# - Asp.net Core 不收集垃圾

c# - Selenium WebDriver 第二次点击不起作用

.net - Try Catch 错误处理的最佳实践

c# - 南希代理请求

c# - 如何从小数中去掉小数部分?

c# - 如何确保同一线程将调用服务器计算机中的 com+ 组件

.net - 如何在 .NET 中使用 XSLT?

c# - 如何从 DataTemplate 获取 XAML 控件的值

c# - 将 Mime 类型添加到虚拟目录