Saturday, February 28, 2015

Parallel For Break (Console Application)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Parallel_For_Break
{

    class Program
    {
        static void Main(string[] args)
        {
            //breaking a parallel for method
            //the break() method is defined in the ParallelLoopState class
            //so you to use a Parallel.For overload whose Action delegate takes a 
            //ParalleloopState type
            /*
             * public static ParallelLoopResult For(
             *                                       int formInclusive,
             *                                       int toExclusive,
             *                                       Action<int,ParallelLoop> body
             *                                       )
             *                                       
            // */
            Console.WriteLine("\n\nExample Number 1\n");
            Parallel.For(1, 201, (i, loopState) => //you do not need to call loopstate you can call it whatever you want
            {
                int j = i;
                if (i > 100) //it will break when reaches 101 .....if we put i == 100 it will break in 100..only breaks the cycles that are above the breaking cycle
                //READ THIS: https://msdn.microsoft.com/en-us/library/dd460721(v=vs.110).aspx
                {
                    //when running, the cycles are random....there is not first cycle or last cycle
                    loopState.Break();
                    Console.WriteLine("Breaking on index: {0}", j);
                    loopState.Break();
                }
                Console.WriteLine("index:{0}  taskid: {1}", j.ToString().PadRight(9), Task.CurrentId);
            });
            //Example
            //Use a Parallel.For that adds all the ints between 1000 and 1200 break when the sum exceeds 5000
            //Display Cycle number and sum 

            Console.WriteLine("\n\nExample Number 2\n");
            long sum = 0;
            Parallel.For(1, 200, (i, loopState) =>
            {
                int j = i;
                sum += j + 1000;
                if (sum > 5000)//it will breake when reach 5000
                {
                    loopState.Break();
                    Console.WriteLine("Breaking Cycle: {0}", j);
                    loopState.Break();
                }
                else
                {
                    Console.WriteLine("Cycle:{0}   sum : {1}", j, sum);
                }

            });
            Console.ReadLine();
        }
    }
}
//The ParalleloopsState clas define 2 methods that allow you to exit a Parallel.For..Break() and Stop() method
//New Project:
//repeat same code using the Stop() method
//Conclude the difference between Break and Stop methods  

No comments:

Post a Comment