简体   繁体   English

找不到任务内创建的目录和文件

[英]Can't find directory and files created inside task

var tasks = new List<Task>();
var path=@"D:\path";

for(int i=0;i<8;i++)
{
    var task = Task.Factory.StartNew(() => {
    DataSet dataset;

    //Some xml work to fill dataset...

    if(!Directory.Exists(path))
        Directory.Create(path);

    dataset.WriteXml(Path.Combine(path, "filename.xml");

    });
    tasks.Add(task);

}

while(tasks.Count>0)
{
    int i = Task.WaitAny(tasks.ToArray());
    tasks.RemoveAt(i);

    string[] files;
    files = Directory.GetFiles(path);
}

We are trying to get files for each task after it will finish its work. 我们正在尝试为每个任务完成工作后获取文件。 But the problem is, when the code comes to Directory.GetFiles() method, it could not find the releated path (Throws DirectoryNotFound exception). 但是问题是,当代码涉及Directory.GetFiles()方法时,它找不到相关的路径(抛出DirectoryNotFound异常)。 But when we look the path manually, there is a folder with xml files. 但是,当我们手动查看路径时,会出现一个包含xml文件的文件夹。 Sometimes code can find the directory but returns no files even there is a file inside the folder. 有时代码可以找到目录,但是即使文件夹中有文件,也不返回文件。 This situation continues till tasks count comes zero. 这种情况一直持续到任务计数为零为止。

I also tried Task.ContinueWith but still not solved. 我也尝试了Task.ContinueWith,但仍未解决。 It looks like synchronization problem because while debuging the code works correctly. 它看起来像同步问题,因为在调试代码时可以正常工作。 Is it possible Task.WaitAny doesn't wait the task completion? Task.WaitAny是否不等待任务完成?

We are using .NET 4.0. 我们正在使用.NET 4.0。

you're missing a backslash in your path, so when concatenating you're writing to 您在路径中缺少反斜杠,因此在连接时要写到

@"D:\path" + "filename.xml"

which is 这是

@"D:\pathfilename.xml"

and NOT 并不是

@"D:\path\filename.xml"

Nothing to do with tasks at all there :) 与那里的任务无关:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM