Parallel for-each loops in .NET C#
April 11, 2014 3 Comments
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.
Hi.
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!
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
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?