1

I have a list which has 100,000 records. I want to iterate throught the list and call a method in C#. I want to run the method in 50 threads inside the list in order to increase performance.

I checked the option of Parallel.Foreach.

but not able to set how many threads should run

  • 5
    You cannot increase compute-bound performance by using using more threads than you have processor cores. Use `Parallel.ForEach()` and let *it* decide how many threads to use. – Matthew Watson Oct 08 '19 at 08:05
  • Could you provide the relevant code, please? Often an optimization matters more than executing in parallel. – Dmitry Bychenko Oct 08 '19 at 08:10
  • Hi , I am calling a web service for each record in a list – user3782554 Oct 08 '19 at 09:10
  • So your workload is I/O bound, not CPU bound. In this case forget about the `Parallel` class and go with the `Task` class. Look [here](https://stackoverflow.com/questions/58272848/parallel-foreach-or-task-whenall-when-involving-async-operations/58274118#58274118) for a bit more details. – Theodor Zoulias Oct 08 '19 at 12:11

1 Answers1

1

Technically, you can specify 50 threads in Parallel.ForEach, e.g.

 Parallel.ForEach(
    list,
    new ParallelOptions() {
      MaxDegreeOfParallelism = 50 // we want 50 threads
    },
    item => {
      //TODO: your code here
    });

However, increasing number of threads (without increasing number of CPU cores) will not bring better performance.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215