Run-Task-Parallelly-in-Csharp-social

Run Tasks Parallelly in C#

Run Tasks Parallelly in C#

Hello folks today I am going to explain you regarding how could we run tasks parallelly,

by using Parallel.Invoke

We need to add System.Threading and System.Threading.Tasks namespaces.

Below is the code snippet to run tasks parallelly in C#.  I have added two method to run parallelly in our C# console application, both methods will return numeric value by 1 second’s interval. These methods will be invoked by Parallel.Invoke and run parallelly.

Note: Parallel.Invoke would be available greater or equal to Framework-4.

 

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

namespace RunTaskParallelly
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Title = "Run tasks parallelly in C#";
            Parallel.Invoke(
                new Action(Method1),
                new Action(Method2)
                );

            Console.ReadLine();
        }

        private static void Method1()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("Method1 - Number: {0}", i);
                Thread.Sleep(1000);
            }
        }

        private static void Method2()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("Method2 - Number: {0}", i);
                Thread.Sleep(1000);
            }
        }
    }
}

Output:

Run-Task-Parallelly-in-Csharp

Leave a Reply