Pattern: Iterator

Topics: Samples and Patterns
Coordinator
Jan 11, 2007 at 10:34 PM

        private static void IteratorTest()
        {
            // Method 1) Iterate using a method that returns IEnumerable<Selector>.
            Port<string> p = new Port<string>();
            p.Push("s1");
            p.Push("s2");
            p.Push("s3");
            // Enumerate over the GetResults "collection", which yields selector items.
            Selector.SelectOneIterator<string>(true, p, GetResults).Run();
 
            // Method 2) Iterate using a collection. This can be used for simple-complex workflow or when you don't need
            // to listen on a primary port to start the iteration, but you want a collection of selectors (each with
            // their own ports) to define the progress. 
            Port<string> p2 = new Port<string>();
            // Add our selectors to the workflow.
            List<Selector> list = new List<Selector>();
            SelectOne<string> s0 = new SelectOne<string>(false, p2, delegate(string s) { Console.WriteLine(s); });
            SelectOne<string> s1 = new SelectOne<string>(false, p2, delegate(string s) { Console.WriteLine(s); });
            list.Add(s0);
            list.Add(s1);
            Selector.Workflow(new DispatchQueue(), list);
            p2.Push("test1");
            p2.Push("test2");
            p2.Push("test3 should not appear");
        }
 
        // Defines dynamic "Collection".
        private static IEnumerable<Selector> GetResults(string item)
        {
            Console.WriteLine("Got port item: {0}", item);
            Port<string> p = new Port<string>();
            p.Push("one");
            p.Push("two");
            yield return Selector.SelectOne(false, p,
                delegate(string s)
                {
                    Console.WriteLine("Inside selector1: {0}", s);
                });
            Console.WriteLine("Completed first selector.");
            yield return Selector.SelectOne(false, p,
                delegate(string s)
                {
                    Console.WriteLine("Inside selector2: {0}", s);
                });
            Console.WriteLine("Completed second selector.");
        }