3

I have 1 method that I want to run in 10 different parallel threads, all will be independent there are no dependency on each other, my problem is that if I have 100 items to process and would like to process 10 at a time then how do in run 10 at a time. I have created a sample code where I am using Parallel.ForEach but what do I need to set so it should run 10 threads at a time and suppose any of the the running task have completed then it should automatically take new one, so all 10 threads should be busy until and unless all items are not completed.

 private void StartAccuracyCalculator() { List<MaterialComposition> lstMaterialComposition = DataHelper.GetMaterialComposition(); Parallel.ForEach(lstMaterialComposition, composition => { try { CalculateAccuracy(composition); } catch (Exception ex) { //LogException(ex) } }); } private void CalculateAccuracy(MaterialComposition composition) { /// actual process to perform } 

suppose lstMaterialComposition get the 100 records from DB so in Parallel.ForEach I want to run only 10 item at a time and any of 10 have completed so a next item from lstMaterialComposition should start.

please suggest is it possible though Parallel.ForEach or is there other option to do it?

1 Answer 1

6

You can use ParallelOptions.MaxDegreeOfParallelism Property to limit the number of tasks.

MaxDegreeOfParallelism The MaxDegreeOfParallelism property affects the number of concurrent operations run by Parallel method calls that are passed this ParallelOptions instance. A positive property value limits the number of concurrent operations to the set value. If it is -1, there is no limit on the number of concurrently running operations.

Parallel.ForEach( lstMaterialComposition, new ParallelOptions { MaxDegreeOfParallelism = 10 }, composition => { try { CalculateAccuracy(composition); } catch (Exception ex) { //LogException(ex) } } ); 
Sign up to request clarification or add additional context in comments.

2 Comments

thanks Adil, setting new ParallelOptions { MaxDegreeOfParallelism = 10 } will aromatically take the next task if any of the running task have completed?
Yes @Neeraj Kumar Gupta.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.