PM's Blog

Pramod Mohanan's notes about ASP.NET, MVC, C#, SQL, jQuery, Bootstrap

Multithreading with a loop using Parallel

In a recent project I had to work with some API calls that allowed only one record at a time. To finish 53000 records took the application more than 7 hours!! damn that sounded like 80s to me. I had to go the multithread way to finish the tasks in acceptable time.

The immediate challenge was to run ‘n’ number of records at a time as obviously I didnt want to do all the 50K+ records in one go. The lovely Parallel of c# came was a no-brainer solution to adopt.

var maximumThreads = 50;
var records = getRecords(); //fetch records 
Parallel.ForEach(records, new ParallelOptions() {MaxDegreeOfParallelism = maximumThreads},
                      record =>
                      {
                          //do the task here or call the method that does the task
                          doTheTask(record);
                      });

thats it, bingo! 50 threads instead of one made the app 50 times faster.

Updated: August 24, 2015 — 3:48 pm

Leave a Reply

Your email address will not be published. Required fields are marked *

PM's Blog © 2018