I have a list of object that I want to execute at the same time.
private List<Calculate_Data> ListOfDataToCalculate = new List<Calculate_Data>();
I have a method that loops through the list of as and call StartCalculate() follow
public async void StartCalculating()
{
foreach (var alldata in ListOfDataToCalculate )
{
alldata.StartCalculate();
}
}
Is there a way to blast them all and make them alldata.StartCalculate() in parallel instead of in sequence? I know that we can use
var calculatetask = Task.Run(() =>
{
alldata.StartCalculate();
});
But is there to do them all at the same time? Some objects are longer to execute and some are faster. The ending does not matter. What's important is doing all at the same time.
Thank you
CodePudding user response:
Use Parallel.ForEach
:
Parallel.ForEach(ListOfDataToCalculate, alldata =>
{
alldata.StartCalculate();
});