Get Directories with Parallel ForEach

2019-09-15 01:29发布

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条回答
Melony?
2楼-- · 2019-09-15 02:34

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();
    }
查看更多
登录 后发表回答