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

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

当我正常运行它时,它每隔一次运行一次,另一次它抛出一个 DirectoryNotFoundException ,就行:
File.WriteAllLines(filePath, CreateRows(TestLineCount, TestSampleCount));

Could not find a part of the path '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/

10-11 18:21