C# 如何并行启动 List<Task>?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13837662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:56:49  来源:igfitidea点击:

How to start a List<Task> in parallel?

c#task-parallel-library

提问by user833115xxx

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

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

在其他地方我有一个List<MyClass>,所以我执行以下操作以获得一个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?

既然我有了 ,我该List<Task>如何并行启动它们?有没有更简洁的方法来编码?

Thanks!

谢谢!

采纳答案by Honza Brestan

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

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

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>.ForEachfor shorter code).

但是,如果您有太多的代码,以至于您想将启动逻辑移动到另一个线程,您可以在另一个线程/任务中调用上述代码(我使用的List<T>.ForEach是较短的代码)。

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.

或者您可以使用 TPL 的Parallel.ForEach. 这仍然会阻止正在执行的线程,直到所有任务都启动,但它将在内部线程池上执行启动操作,因此对于大量项目和一些空闲的 CPU 内核/线程,它可能会大大加快启动速度。

Parallel.ForEach(myTaskList, task => task.Start());

回答by sphair

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

我可能误解了您的问题,但这不就是在每项任务上都调用 Start 吗?

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

Waiting for all the tasks to finish:

等待所有任务完成:

Task.WaitAll(myTaskList.ToArray());