Skip to main content

Parallel ForEach loop in C# with Example

Parallelism with forEach loop will be able to handle multiple records to process in the loop parallel. Compared to foreach loop parallel.foreach loop will process faster. But it is not recommending to use if there is dependency.

 Example:


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

namespace ParllForEch
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> Alphabets = new List<string>();
            Alphabets.Add("A");
            Alphabets.Add("Aa");
            Alphabets.Add("Aaa");
            Alphabets.Add("B");
            Alphabets.Add("Bb");
            Alphabets.Add("Bbb");
            Alphabets.Add("C");
            Alphabets.Add("Cc");
            Alphabets.Add("Ccc");
            Alphabets.Add("D");
            Alphabets.Add("Dd");
            Alphabets.Add("Ddd");
            Alphabets.Add("E");
            Alphabets.Add("Ee");
            Alphabets.Add("Eee");
            Alphabets.Add("F");
            Alphabets.Add("Ff");
            Alphabets.Add("Fff");
            Alphabets.Add("G");
            Alphabets.Add("Gg");
            Alphabets.Add("Ggg");
            Alphabets.Add("H");
            Alphabets.Add("Hh");
            Alphabets.Add("Hhh");
            Alphabets.Add("I");
            Alphabets.Add("Ii");
            Alphabets.Add("Iii");

            Parallel.ForEach(Alphabets, new ParallelOptions { MaxDegreeOfParallelism = 5 }, fruit =>
                {
                    Console.WriteLine("Fruit Name: {0}, Thread Id= {1}", fruit, Thread.CurrentThread.ManagedThreadId);
                }
                );
            Console.ReadLine();
        }
    }
}

OutPut :


Comments

  1. Welcome to a new experience in learning ABCD for kids. Introducing the Kids Alphabet AR app.
    https://bit.ly/2P9HGSL

    ABCD for Kids

    Learn ABCD

    Kids Alphabets

    ReplyDelete

Post a Comment