问题
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:
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)
}
}
);
来源:https://stackoverflow.com/questions/42688112/how-to-run-a-task-in-max-defined-parallel-threads-using-c-net-4-0