0

我有一个在目录上递归并构建树的方法:

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 知识太原始了。

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

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();
}

我将如何完成它?

编辑:

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

4

1 回答 1

0

但是你已经做到了!

    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();
    }
于 2012-06-30T04:12:18.177 回答