Help using a parallel task library

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.

+3
source share
1 answer

, , , , , :

DoSomeWork(someValue));

someValue, , , :

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

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

, , , , , , .

+5

Source: https://habr.com/ru/post/1790578/


All Articles