Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
164 views
in Technique[技术] by (71.8m points)

c# - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...