Get Directories with Parallel ForEach

自闭症网瘾萝莉.ら 提交于 2019-12-11 18:48:11

问题


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

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.

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

How would I finish it?

EDIT:

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.


回答1:


But you already did it!

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


来源:https://stackoverflow.com/questions/11271094/get-directories-with-parallel-foreach

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!