Parallel tree traversal in C#

前端 未结 5 2029
轻奢々
轻奢々 2021-02-05 19:28

I need to traverse a tree quickly, and I would like to do it in parallel. I\'d rather use the parallel extensions than manually spin up a bunch of threads.

My current co

5条回答
  •  时光取名叫无心
    2021-02-05 19:44

    I might be missing something, but I don't see the need for a while at all. The while is just ensuring that you iterate over every node.

    Instead just call your function recursively for each node in the tree.

    public void Traverse(Node root)
    {         
        if (root.Property = someValue) DoSomething(node);    
        Parallel.ForEach(root.Children, node => Traverse(node));
    } 
    

    edit: of course the alternative, if you prefer to process horizontally rather than vertically and your expensive operation is DoSomething, is to do the Traverse first.

    public IEnumerable Traverse(Node root)
    {
        // return all the nodes on this level first, before recurring
        foreach (var node in root.Children)
        {
            if (node.Property == someValue)
                yield return node;
        }
    
        // next check children of each node
        foreach (var node in root.Children)
        {
            var children = Traverse(node);
            foreach (var child in children)
            {
                yield return child;
            }
        }
    }
    
    Parallel.ForEach(Traverse(n), n => DoSomething(n));
    

提交回复
热议问题