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.
I don’t know if this is causing execution to stop, but perhaps it’s because you’re closing over the loop variable here:
You need to create a local variable and assign
someValueto it, and then use that local variable, as is described in my linked question, like so:Again, I’ve no idea if that is the problem to your deadlock issue, but that is one issue that will most likely cause problems.