Running your application in parallel cores using Parallel

In C# language there is a way to use all the available cores in your computer simultaneously to run your application logic. This will improve the processing time of the application and lead you to better performance.

NOTE –  Think twice whether you’ve applied parallelism to the correct logic in your application. If not, you may end up with taking longer time than single processing.

It is pretty much clear that now days almost all the computers are equipped with more than one core and as developers, we should use those cores for better performances of our application.

In the System.Threading.Tasks namespace you can find a static class called Parallel which can use to run your application simultaneously in your cores.

I have created a small console application to try out this parallel mechanism. For that, I created a small method that loop through million (1,000,000) times.

        // Million counter
        public static void MillionCounter()
        {
            for (int i = 0; i < 1000000; i++)
            {
                Console.WriteLine(i + " Iteration processing..");
            }
        }

And another method to run this millions 10 times.

        // Run counter without parallel execution
        public static void NotParallelExecution()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(i + "Iteration Started");
                MillionCounter();
                Console.WriteLine(i + "Iteration Completed");
            }
        }

My full console application code which doesn’t have any parallel method is as below. After I ran it with a stopwatch it took around 3:10:73(min) to finish whole iterations with my 8 core machine.

1

Below is the Performance monitor results when I was running the application. You can see that the time of a processor (Yellow line) is been increased more than other processors at the time when I was running the application which is highlighted by red square. While keeping that in the mind, will move into the parallelism.

Screenshot (3)

Parallel.For()

As I mentioned earlier, before starting with Parallel you need to reference System.Threading.Tasks

Parallel doesn’t care about the order of the execution. That means it doesn’t execute from 0 to 10. It may start from 5 then 0, 1, 9 , 10, 8 … likewise and wait till every iteration finish.

The Parallel is a static class and has three basic methods that can use in your application.

  • Parallel.Invoke() –  Run many methodds parallely.
  • Parallel.For() – Run for loop parallely.
  • Parallel.ForEach() –  Run foreach loop parallely.

The ForEach and For functions help to run each iteration in parallel. According to the above scenario, the most suitable method to use is Parallel.For(). Let’s see how we can run above loop parallelly. When you use Parallel.For()  you can use the same method as a loop method.

            //Parallel execution
            Parallel.For(0, 10, i =>
            {
                Console.WriteLine(i + "Iteration Started");
                MillionCounter();
                Console.WriteLine(i + "Iteration Completed");
            });

According to the above code Parallel.For(firstParam, secondParam, thirdParam),

  • firstParam – Starting index of the loop. (0 – according to above)
  • secondParam – Ending index of the loop. (10 – according to above)
  • thirdParam –  Method or the action to execute 10 times. (MillionCounter(); – accroding to above)

With the above changes, my whole code as below and I ran the application.

2

When I was running the application, my Performance monitor for processor time gave me the below reading and it took around 2:20:63 (min) finish which is below than previous running time.

And in the red square, you can see that how suddenly my whole processors started to go up by the same time.

Screenshot (8)

And when it was reaching to finish, the monitor behave like below,

Screenshot (10)

That is one way to use Parallel which will help to consume all the cores in a computer for better performance. But again you must note that,

Use Parallel intelligently, otherwise, it will take more time and more resources than your expectation and eng up with low performance.

For an example, let’s say you want to get sum of ten numbers. What is much faster?by counting yourself or giving each pair to 5 people, get the sum and again sum all pairs to get the total sum?

Parallel.Invoke()

With the Parallel.Invoke()  you can invoke any number of void methods in parallel cores. See below code and try. Note that order of execution is not sequential.

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ParallelConsoleSample
{
    class Program
    {
        static void Main(string[] args)
        {
            //Parallel execution
            Parallel.Invoke(() => Method1(), () => Method2(), () => Method3());
            Console.ReadLine();
        }


        // Method 1
        public static void Method1(){
            Console.WriteLine("Method 1 started");
            Thread.Sleep(5000);
            Console.WriteLine("Method 1 finished");
        }
        // Method 2
        public static void Method2()
        {
            Console.WriteLine("Method 2 started");
            Thread.Sleep(1000);
            Console.WriteLine("Method 2 finished");
        }
        // Method 3
        public static void Method3()
        {
            Console.WriteLine("Method 3 started");
            Thread.Sleep(2500);
            Console.WriteLine("Method 3 finished");
        }

    }
}

3

Parallel.ForEach()

Parallel.ForEach() is also very similar to Parallel.For() function as above. You can try below code sample which will use the available cores for each iteration. Note that it is much better to use Parallel if there are much more complex scenarios to address in each and every iteration. Otherwise, the below example will take more time than single processor execution.

using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace ParallelConsoleSample
{
    class Program
    {
        static void Main(string[] args)
        {
            var items = Enumerable.Range(0, 10);

            Parallel.ForEach(items, item=> {
                Console.WriteLine(item + " Iteration started");
                Thread.Sleep(1000);
                Console.WriteLine(item + " Iteration finished");
            });
            Console.ReadLine();
        }
    }
}

4

That is the end of my short post about the Parallel in C# language. Hope you gain some knowledge from this article and I like to hear about your feedback.

Cheers! Happy Coding!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s