通过并行ForEach获取目录 [英] Get Directories with Parallel ForEach

查看:86
本文介绍了通过并行ForEach获取目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个遍历目录并构建树的方法:

I've got a method that recurses over a directory and builds a Tree:

public void RecurseFolders(TreeNode mainNode) {
  DirectoryInfo nodeDir = new DirectoryInfo(mainNode.Tag.ToString());
  try {
    foreach (var dir in nodeDir.GetDirectories()) {
      int index = GetSystemIcon(dir.FullName, treeView1.ImageList, false);
      var subNode = new TreeNode(dir.Name, index, index);
      subNode.Tag = dir.FullName;
      mainNode.Nodes.Add(subNode);
      RecurseFolders(subNode);
    }
  } catch (UnauthorizedAccessException err) {
    Console.WriteLine(err);
  }
}

我想做的是找到一种写的方法Parallel.ForEach 出来了,但是我对LINQ的了解还是太陌生了.

What I'd like to do with this is find a way to write a Parallel.ForEach out of it, but my LINQ knowledge is too virgin.

很显然,我无法将TreeNode传递给线程,因此我将签名修改为更通用.据我所知:

Obviously, I can't pass the TreeNode into the thread, so I modified the signature to be more generic. This is as far as I got:

public string[] RecurseFolders(string dirString) {
  List<string> list = new List<string>();
  DirectoryInfo nodeDir = new DirectoryInfo(dirString);
  Parallel.ForEach(nodeDir.GetDirectories(), dir => {
    // how do I write this?
  });
  return list.ToArray();
}

我该怎么办?

这将从我们的网络存储驱动器中提取目录和文件列表.当前,通过网络获取信息是我们的瓶颈,但这对我来说是学习一些并行处理技术的好地方.

This is pulling a list of directories and files off of our network storage drive. Getting the information across the network is currently our bottleneck, but it is a good place for me to learn some Parallel Processing techniques.

推荐答案

但是您已经做到了!

    public string[] RecurseFolders(string dirString) {
      List<string> list = new List<string>();
      DirectoryInfo nodeDir = new DirectoryInfo(dirString);
      Parallel.ForEach(nodeDir.GetDirectories(), dir => {
//Just continue writing here. This is an Action. Google it for more info. But for the purposes of this example you may consider it as method which will be called for each of the items
      });
      return list.ToArray();
    }

这篇关于通过并行ForEach获取目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆