Sample: Parallel Calculation with Scatter/Gather

Topics: Samples and Patterns
Coordinator
Jan 11, 2007 at 1:22 AM

        /// <summary>
        /// Scatter and gather parallel calculations demo.
        /// </summary>
        private static void ParallelCalcTest()
        {
            Port<int> inPort = new Port<int>();
            Port<int> resultPort = new Port<int>();
 
            // Register a handler that will get activated concurrently.
            Selector.SelectOne(true, true, inPort,
                delegate(int num)
                {
                    int r = num * 2;
                    Console.WriteLine("Result:{0} ThreadID:{1}", r, Thread.CurrentThread.ManagedThreadId);
                    resultPort.Push(r);
                    Thread.Sleep(10);   // Force a sleep to help kick-in multiple threads for demo.
                }).Run();
            
            // Scatter work.
            for (int i = 0; i < 20; i++)
            {
                inPort.Push(i);
            }
 
            // Gather results. Do an async (i.e. non-blocking) wait for exactly 20 results.
            Selector.SelectMany(false, resultPort, 20,
                delegate(int[] array)
                {
                    Console.WriteLine("Got results:");
                    foreach (int i in array)
                    {
                        Console.WriteLine(i);
                    }
                }).Run();
        }