Scatter-Gather Pattern

Topics: Samples and Patterns
Coordinator
Jan 8, 2007 at 4:18 AM
        
        /// <summary>
        /// Scatter work and wait for all to complete asyncronously.
        /// </summary>
        private static void ScatterGather()
        {
            Port<int> replyPort = new Port<int>();
            Port<int> p0 = new Port<int>();
            Port<int> p1 = new Port<int>();
            Port<int> p2 = new Port<int>();
            p0.Push(2);
            p1.Push(4);
            p2.Push(6);
 
            // Scatter work. We just send numbers to workers which multiply by 2 and send result to replyPort.
            Selector.Activate(null,
                Selector.SelectOne(false, p0,
                    delegate(int num)
                    {
                        replyPort.Push(num * 2);
                    }),
                Selector.SelectOne(false, p1,
                    delegate(int num)
                    {
                        replyPort.Push(num * 2);
                    }),
                Selector.SelectOne(false, p2,
                    delegate(int num)
                    {
                        replyPort.Push(num * 2);
                    })
            );
 
            // Gather results. Wait for exactly three items before Handler is run.
            Selector.Activate(null,
                Selector.SelectMany<int>(false, replyPort, 3, 
                    delegate(int[] results)
                    {
                        Console.WriteLine("Results:");
                        foreach(int i in results)
                            Console.WriteLine(i);
                    })
            );
        }