User987 User987 - 1 year ago 83
ASP.NET (C#) Question

Improving performance of Parallel.For in C# with more methods

Recently I've stumbled upon a Parralel.For loop that performs way better than a regular for loop for my purposes.

This is how I use it:

Parallel.For(0, values.Count, i =>Products.Add(GetAllProductByID(values[i])));

It made my application work a lot faster, but still not fast enough. My question to you guys is:

  1. Does Parallel.Foreach performs faster than Parallel.For?

  2. Is there some "hybrid" method with whom I can combine my Parralel.For loop to perform even faster (i.e. use more CPU power)? If yes, how?

Can someone help me out with this?

Answer Source

If you want to play with parallel, I suggest using Parallel Linq (PLinq) instead of Parallel.For / Parallel.ForEach , e.g.

 var Products = Enumerable
   .Range(0, values.Count)
   //.WithDegreeOfParallelism(10) // <- if you want, say 10 threads
   .Select(i => GetAllProductByID(values[i]))
   .ToList(); // <- this is thread safe now

With a help of With methods (e.g. WithDegreeOfParallelism) you can try tuning you implementation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download