Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help with Task parallel library usage

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.

like image 947
stackoverflowuser Avatar asked Dec 08 '25 15:12

stackoverflowuser


1 Answers

I don't know if this is causing execution to stop, but perhaps it's because you're closing over the loop variable here:

DoSomeWork(someValue));

You need to create a local variable and assign someValue to it, and then use that local variable, as is described in my linked question, like so:

foreach(var someValue in aCollection)
{
   var localCopy = someValue;

   var t = Task.Factory.StartNew(() => DoSomeWork(localCopy));
   tasks.Add(t);
}

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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!