如何启动List< Task>在平行下? [英] How to start a List<Task> in parallel?

查看:48
本文介绍了如何启动List< Task>在平行下?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回 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
    }
}

在其他地方,我有一个 List< MyClass> ,所以我执行以下操作以获取一个 List< Task> :

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

现在我有了 List< Task> ,如何并行启动它们?有没有更简洁的编码方式?

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

谢谢!

推荐答案

并行启动"是什么意思?当您运行 Task 时,它会在另一个线程上执行,因此您的意思可能很简单:

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

但是如果您有太多这样的内容,您想将启动逻辑移到另一个线程,则可以在另一个线程/任务中调用上述代码(我正在使用 List< T> .ForEach 以获取较短的代码.

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

或者您可以使用TPL的 Parallel.ForEach .在所有Tasks启动之前,这仍然会阻塞执行线程,但是它将在内部线程池上执行start操作,因此对于大量项目和一些可用的CPU内核/线程,它可能会大大加快启动速度.

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

这篇关于如何启动List&lt; Task&gt;在平行下?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆