Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start a List<Task> in parallel?

I have an object that returns a System.Threading.Tasks.Task:

public class MyClass 
{
    public Task GetTask(object state, CancellationToken cancellationToken)
    {
        return new Task(Execute, state, cancellationToken);
    }

    public void Execute(object context)
    {
        //do stuff
    }
}

Elsewhere I have a List<MyClass>, so I do the following to get a List<Task>:

var myTaskList = myClassList.Select(p => p.GetTask(null, cancellationToken)).ToList();

Now that I have the List<Task>, how can I start them all in parallel? Is there a more concise way to code this?

Thanks!

like image 303
user833115xxx Avatar asked Dec 12 '12 10:12

user833115xxx


People also ask

Does task WhenAll run in parallel?

WhenAll() method in . NET Core. This will upload the first file, then the next file. There is no parallelism here, as the “async Task” does not automatically make something run in in parallel.

How do you wait for parallel ForEach?

You don't have to do anything special, Parallel. Foreach() will wait until all its branched tasks are complete. From the calling thread you can treat it as a single synchronous statement and for instance wrap it inside a try/catch.


2 Answers

What do you mean by "start them in parallel"? When you run the Task, it executes on another thread, so you probably mean simply:

foreach(var task in myTaskList)
{
    task.Start();
}

But if you have so many of them that you want to move the starting logic to another thread, you can either call the above code in another thread/task (I'm using List<T>.ForEach for shorter code).

Task.Factory.StartNew(() => myTaskList.ForEach(task => task.Start()));

Or you can use TPL's Parallel.ForEach. That would still block the executing thread until all the Tasks are started, but it will execute the start action on an internal threadpool, so for large numbers of items and some free CPU cores/threads, it might speed up the starting considerably.

Parallel.ForEach(myTaskList, task => task.Start());
like image 114
Honza Brestan Avatar answered Oct 15 '22 16:10

Honza Brestan


I might be misunderstanding your question, but isn't it just to call Start on every task?

foreach(Task task in myTaskList) 
{
    task.Start();
}

Waiting for all the tasks to finish:

Task.WaitAll(myTaskList.ToArray());
like image 37
sphair Avatar answered Oct 15 '22 17:10

sphair