I am trying to schedule a function call for a sequence of items using Task parallel library.
The following 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 the below works
Task.WaitAll(aCollection.Select(a => Task.Factory.StartNew(() => DoSomeWork(a))).ToArray());
For the first approach it executes once and then stops. I am not sure if its overwriting the reference or something. Can someone pls. explain?
Also is there a way to pass some sequence number to Task that can be used to identifiy which task was scheduled first. I mean I want to wait for all the tasks to complete but then order the results based on the sequence in the collection.