是目录.CreateDirectory异步或其他

本文关键字:其他 异步 CreateDirectory | 更新日期: 2023-09-27 18:05:21

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

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总是在那里?

是目录.CreateDirectory异步或其他

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

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