Skip to main content
 首页 » 编程设计

c#之C# 中的任务并行 (TPL) 和任务调度

2024年02月23日15bjzhanghao

根据 Microsoft ( link ),有两种启动任务的方法:隐式 和显式。

假设我在主线程中创建了 4 个不同的任务,分别称为 task1、task2、task3 和 task4。

case1:我在主线程中明确地运行它们:

task1.Start(); 
task2.Start(); 
task3.Start(); 
task4.Start(); 

案例 2:我在主线程中使用 Parallel.Invoke 方法隐式运行它们:

Parallel.Invoke(task1, task2, task3, task4); 

我注意到的唯一区别是在 case2 中,主线程挂起直到 Invoke() 返回。

我的问题是关于任务调度程序。 任务调度程序在 case1 和 case2 中的 4 个任务在调度方面是否不同,或者它们完全等同?

在我上面提到的同一个链接中,我们读到:

Behind the scenes, tasks are queued to the ThreadPool, which has been enhanced with algorithms (like hill-climbing) that determine and adjust to the number of threads that maximizes throughput. This makes tasks relatively lightweight, and you can create many of them to enable fine-grained parallelism. To complement this, widely-known work-stealing algorithms are employed to provide load-balancing.

请您参考如下方法:

This blog post来自 Parallel 团队的应该可以回答您的一些问题。

简短回答:对于任务,您必须在主线程上执行 Task::WaitAll(...) 以防止退出,因为 Parallel::Invoke 实际上会为您处理这个问题。除此之外,没有别的,因为在 Parallel::Invoke 下使用相同的 TPL 基础设施。