Parallel For and Foreach

Ive finally used the greatness known as the parallel.for and parallel.foreach. I just dont understand how I’ve lived so long without this greatness that has been bestowed upon us in the world known as .net. A parallel loop allows you to run each of the iterations of the loop simultaneously on separate threads at the same time. It uses what threads you have available to decide when it will run. Here are some code snippets below:


System.Threading.Tasks.Parallel.For(0, numOfIterations, Sub(i)
‘do whatever with your i var that you want to happen in parallel
End Sub)


System.Threading.Tasks.Parallel.ForEach(result.AssessmentDatasets(i).Tables(“Assessment”).AsEnumerable(), Sub(row)

”do whatever with your row var that you want to happen in parallel

End Sub)

If you look at the first var im just looping through some variable that will be incrementing for what ever the purpose of the for loop would be.

On the second one, the foreach, im looping through the rows of a datatable and processing each row in parallel. The AsEnumeralble is not a part of the datatable until you add a reference to System.Data.DataSetExtensions. once you add it, that function will become available.

This entry was posted in Uncategorized and tagged , , , , , , . Bookmark the permalink.

6 Responses to Parallel For and Foreach

Leave a Reply

Your email address will not be published.