如何确保在当前行完成之前不执行下一行代码

时间:2012-06-21 23:05:55

标签: c# wait

DirectoryInfo di = new DirectoryInfo(lPath); 
DirectoryInfo dest = new DirectoryInfo(lPath9);
if (!dest.Exists) dest.Create(di.GetAccessControl());
string mapDirName = di.FullName;
di.Delete(true);
Thread.Sleep(20);  // let the process wait a bit       
dest.MoveTo(mapDirName);           
Thread.Sleep(20);  // let the process wait a bit

以上代码大部分时间都有效。但是,有时某些子目录在dest重命名为di后会丢失。

我认为这是因为重命名已在删除完成之前启动。 在重命名之前,我可以添加一个while循环来检查di的存在。 如,

int i=0;
While (di.Exists && i < 10) {
     Thread.Sleep(10000);
     i++;
}

仍然只能等待10000 * 10毫秒。没有进入无限循环就没有确定的方法。

2 个答案:

答案 0 :(得分:1)

我有类似的情况,我需要确保在继续之前删除所有内容。这就是我设法绕过它的方式。似乎到目前为止工作

var dir = new DirectoryInfo(location);
while (dir.Exists)
{
    dir.Delete(true);
    dir = new DirectoryInfo(location);
}

答案 1 :(得分:0)

为什么不循环遍历目录中的文件,而不是在移动目录之前等待任意时间?

foreach (FileInfo file in di.GetFiles())
{
    File.Delete( file );
}

dest.MoveTo( mapDirName );
相关问题