Parallel Programming in C#

 

using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;


namespace ParallelProgrammingDemo
{
    class Program
    {
        // Main Entry point of execution.
        static void Main(string[] args)
        {
            // Create a Cancellation Token, to provide user a flexibility to cancel an operation.
            CancellationTokenSource cts = new CancellationTokenSource();

            // Start a new Task, to take user input from console especially for Cancellation process
            // in this case it is defaulted to key stroke'c'.
            Task.Factory.StartNew(() =>
            {
                if (Console.ReadKey().KeyChar == 'c')
                    cts.Cancel();
            });

            int result = 0;

            /* 1. Use Parallel.For (introduced in .Net 4.0) for parallel processing on multiple threads.
             * 2. When a iterative long running operation needs to be performed, then using Parallel.For
             *    will help in spanning these iterations on multiple threads and on final stage combining
             *    all successive inputs.
             * 3. There is also a provision for breaking/stopping these iteration by setting up LoopState.
             * 4. We can also set the initial value (as a param) for all threads which are spanning across.
             * 5. Parameters Definition - 
             *      a) Begin iteration FROM
             *      b) End iteration TO
             *      c) Set initial value for threads
             *      d) Logic which needs to be executed for every iteration (this delegate takes present 
             *         iteration state, overall loop state and thread initial value.
             *      f) delegate to synchronize all threads final values. This will be executed at the end.
             * 6. For this example I took threads initial values as 0. Iterative logic consists of a long
             *    running task using Thread.Sleep(30), for sake of understanding I am printing different
             *    thread Ids. Also logic consists of handling user cancellation trigger.   
             * 7. This sample prints total number of iterations.
             */
            Parallel.For(
                0,
                20,
                () => 0,
                (i, loopState, initVal) =>
                {
                    Console.CursorLeft = 0;
                    Console.WriteLine("Thread ID : {0}", Thread.CurrentThread.ManagedThreadId);
                    for (int j = 0; j < 100; j++)
                    {
                        Thread.Sleep(30);
                    }

                    if (cts.Token.IsCancellationRequested)
                        loopState.Stop();

                    return initVal + 1;
                },
            loopState => Interlocked.Add(ref result, loopState));

            // Print Result to console
            Console.WriteLine("Result : " + result);
            Console.WriteLine("Press the Enter key to exit.");
            Console.ReadLine();
        }
    }
}

Output –

Full Execution –

ParallelFor1

Cancelled Execution –

ParallelFor2

You may also like...