I am trying to schedule a function call for a sequence of elements using the parallel Task library.
Does not work
List<Task> tasks = new List<Task>();
foreach(var someValue in aCollection)
{
var t = Task.Factory.StartNew(() => DoSomeWork(someValue));
tasks.Add(t);
}
Task.WaitAll(tasks.ToArray());
But below works
Task.WaitAll(aCollection.Select(a => Task.Factory.StartNew(() => DoSomeWork(a))).ToArray());
For the first approach, it runs once and then stops. I'm not sure if his rewriting links or something else. Maybe someone pls. to explain?
There is also a way to pass some sequence number into a task, which can be used to identify which task was planned first. I mean, I want to wait for the completion of all tasks, but then arrange the results based on the sequence in the collection.
source
share