Parallel for-each loops in .NET C#

It’s trivial to create parallel for-each loops in .NET using the built-in Parallel class. It has a ForEach() method with a wide range of overloaded varieties. One of the easier ones accepts 2 parameters:

  • An IEnumerable object
  • An Action of T which is used to process each item in the list

The parallel ForEach loop will process any type of object in an IEnumerable enumeration. Example:

List<string> dataList = new List<string> 
         "this", "is", "random", "sentence", "hello", "goodbye"

Parallel.ForEach(dataList, item =>
	Console.WriteLine("Item {0} has {1} characters",
		item, item.Length);

Run the code and you’ll see that the items in the string list are not processed sequentially.

View the list of posts on the Task Parallel Library here.


About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

3 Responses to Parallel for-each loops in .NET C#

  1. bahman says:

    i have big list of customers (120K) . now to process this list took 36 hours. how can do paraller process or any solution to reduce the time!

    • Andras Nemes says:

      Hello, is each customer processed one after the other in a sequential manner? In that case you can process them in batches where each customer in a batch is processed in its own thread. The size of the batch depends on the server’s capabilities but you’ll need to experiment. If you have several servers for this purpose then you can even distribute the batches to the servers to make the process even faster. //Andras

      • bahman says:

        sequential is not important. i can pick up any client and any time to process.
        but i have to call 3 api for each client and order of api is important.
        i cant use several server!
        can you help me with code?

Leave a Reply

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

You are commenting using your 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

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: