Search code examples
c#multithreadingcallbackcancellation

Make IEnumerable method async


I have the following node:

class Node
{
    public string Name;        
    public IEnumerable<Node> Children;
}

I have the following extension method:

public static class ExtensionMethods
{
    public static IEnumerable<Node> TraverseTree(this Node root)
    {
        if (root.Children != null)
        {
            foreach (var child in root.Children)
            {
                var nodes = TraverseTree(child);
                foreach (var node in nodes)
                {
                    yield return node;
                }
            }
        }

        yield return root;
    }       
}

I want to search for a node in the tree with the name "Foo". In order to do so I do:

Node myNode = /* some large tree! */
var search = myNode.TraverseTree().Where(x=>x.Name == "Foo").FirstOrDefault();

I have 3 goals

  1. Have the method TraverseTree traverse the tree with yield (IEnumerable) so that if the 3th node happens have the name == "Foo" then I do not have to traverse the entire tree. Right now this case is true.
  2. Make the method TraverseTree run on a separate thread because it may take a long time to find. Therefore I guess the TraverseTree method should take a callBack parameter?
  3. Lastly it will be nice to be able to cancel that operation. Do i need to pass to that method a cancelation token as well?

What is the correct way of doing this?

Sorry I forgot to mention I am using .Net Framework 4.0


Solution

    1. This is already done with the code that you have. Yay for deferred execution.
    2. By far the easier way of doing this is to keep the method synchronous and move the whole query into another thread.
    3. Yes, a CancellationToken that is checked by either the traversal algorithm, your child selector, or both, is certainly something you could add. The other option is to just have whatever it is that's waiting on the result of the traversal stop waiting, rather than trying to actually stop the computation from happening.