Friday, March 6, 2015

Five Parallel loop in Console Application


using System.Threading.Tasks;
using System.Collections.Concurrent; //Added to use BlockingCollection
using System.Threading; //Added to use CancellationTokenSource

namespace ZauBawk_FiveParallel_Lab
{

    class Program
    {
        static void Main(string[] args)
        {
            // 1. Create a CancellationTokenSource object
            CancellationTokenSource cts = new CancellationTokenSource();
            // 2. create a ParallelOptions object
            ParallelOptions po = new ParallelOptions();
            // 3. Assign the CancellationToken property of the ParallelOptions
            //    to the CancellationTokenSource.Token property
            po.CancellationToken = cts.Token;

        repeat:
            Console.WriteLine("Choose a parallel loop to run: ");
            Console.WriteLine("\t1. Parallel.For provide break statement");
            Console.WriteLine("\t2. Parallel.Foreach provide break statement");
            Console.WriteLine("\t3. Paralell.For provide stop statment");
            Console.WriteLine("\t4. Paralell.Foreach provide stop statment");
            Console.WriteLine("\t5. Paralell.Foreach provide cancellation");

            Console.Write("\nIndex number of loop to run: ");
            int selection = int.Parse(Console.ReadLine());
           
            switch (selection)
            {
                case 1: //1. Parallel.For provide break statement
                    {
                        Parallel.For(1, 5001, (root, loopState) =>
                        {
                            int j = root;
                            double result = SumRootN(root);
                            if (root > 50) //break when reaches 50 .....
                            {
                               
                                loopState.Break();
                                Console.WriteLine("Breaking on index: {0}", j);
                            }
                           
                            Console.WriteLine("index:{0}  taskid: {1} Result: {2}", j.ToString().PadRight(9), Task.CurrentId, result);
                        });
                    }
                    break;
                case 2: //2. Parallel.Foreach provide break statement
                    {
                        int[] nums = Enumerable.Range(1, 5001).ToArray();
                        Parallel.ForEach(nums, (root, loopState) =>
                        {
                            int j = root;
                            double result = SumRootN(root);
                            if (root > 100) //break when reaches 50 .....
                            {
                                loopState.Break();
                                Console.WriteLine("Breaking on index: {0}", j);
                                //loopState.Break();
                            }
                            Console.WriteLine("index:{0}  taskid: {1} Result: {2}", j.ToString().PadRight(9), Task.CurrentId, result);
                        });

                    }
                    break;
                case 3: //3. Paralell.For provide Stop statment
                    {
                        Parallel.For(1, 5001, (root, loopState) =>
                        {
                            int j = root;
                            double result = SumRootN(root);
                            if (root == 200) //Stop when reaches 50 .....
                            {
                               
                                loopState.Stop();
                                Console.WriteLine("Stop on index: {0}", j);
                            }
                            Console.WriteLine("index:{0}  taskid: {1} Result: {2}", j.ToString().PadRight(9), Task.CurrentId, result);
                        });
                    }
                    break;
                case 4: //4. Paralell.Foreach provide Stop statment
                    {
                        int[] nums = Enumerable.Range(1, 5001).ToArray();
                        Parallel.ForEach(nums, (root, loopState) =>
                        {
                            int j = root;
                            double result = SumRootN(root);
                            if (root == 300) //Stop when reaches 50 .....
                            {
                               
                                loopState.Stop();
                                Console.WriteLine("Stop on index: {0}", j);
                            }
                            Console.WriteLine("index:{0}  taskid: {1} Result: {2}", j.ToString().PadRight(9), Task.CurrentId, result);
                        });
                    }
                    break;
                case 5:
                    {
                        //Add a task that check the keyboard for the character 'c' (cancel)
                        Task.Factory.StartNew(() =>
                        {
                            if (Console.ReadKey().KeyChar == 'c')
                                cts.Cancel();
                            Console.WriteLine("\n*Parallel.ForEach, Request to cancel was made");
                        });

                        try
                        {
                            int[] nums = Enumerable.Range(1, 5001).ToArray();
                            Parallel.ForEach(nums, (root, loopState) =>
                            {
                                int j = root;
                                double result = SumRootN(root);
                                Console.WriteLine("index:{0}  taskid: {1} Result: {2}", j.ToString().PadRight(9), Task.CurrentId, result);
                                po.CancellationToken.ThrowIfCancellationRequested();
                            });

                        }
                        catch (AggregateException aggrEx)
                        {
                            //since the aggregation exception is just a collection of all exceptions thrown inside the inner tasks, use foreach to sequence thru them
                            foreach (Exception ex in aggrEx.InnerExceptions)
                            {
                                if (ex is ArgumentException)
                                    Console.WriteLine(ex.Message);
                                else
                                    throw ex;
                            }
                        }
                    }
                    break;
                default:
                    {
                        Console.WriteLine("Sorry, Invalid Selection");
                    }
                    break;
            }
            Console.ReadLine();
            Console.Clear();
            goto repeat;

        }
        //======================================================================
        //Method to sum root
        static double SumRootN(int root)
        {
            double result = 0;
            for (int i = 1; i <= 10000; i++)
            {
                result += Math.Exp(Math.Log(i) / root);
            }
            return result;
        }
    }
}
///1. Parallel.For provide break statement
///2. Parallel.Foreach provide break statement
///3. Paralell.For provide break statment
///4. Paralell.Foreach provide break statment
///5. Paralell.Foreach provide cancellation
/////..https://msdn.microsoft.com/en-us/library/dd460721(v=vs.110).aspx

No comments:

Post a Comment