c# - 使用任务并行库有什么意义

标签 c# task-parallel-library

我有一台四核电脑。

我曾考虑过使用任务并行库以编程方式实现多核处理。然而,当我在 Google 上搜索示例时,我得知 CPU 会自动处理此问题,最好不要管它。

现在,我在 Code Project 上发现另一篇文章赞扬了这个库。

使用这个库有什么好处吗?

谢谢

最佳答案

除非您的应用程序主动利用并行处理,否则操作系统和 CPU 都不会自动为您执行此操作。操作系统和 CPU 可能会在多个内核之间切换应用程序的执行,但这并不会使应用程序在不同的内核上同时执行。为此,您需要使您的应用程序能够至少并行执行部分内容。

根据MSDN Parallel Processing and Concurrency in the .NET Framework在 .NET 中进行并行处理基本上有三种方法:

  1. 托管线程,您可以自己处理线程及其同步。
  2. 各种异步编程模式。
  3. .NET Framework 中的并行编程,任务并行库PLINQ 都是其中的一部分。

根据 MSDN 文章,使用 TPL 的原因包括它和随附的工具

simplify parallel development so that you can write efficient, fine-grained, and scalable parallel code in a natural idiom without having to work directly with threads or the thread pool.

Threads vs. Tasks对于在线程和 TPL 之间做出决定有一些帮助 结论是:

The bottom line is that Task is almost always the best option; it provides a much more powerful API and avoids wasting OS threads.

The only reasons to explicitly create your own Threads in modern code are setting per-thread options, or maintaining a persistent thread that needs to maintain its own identity.

关于c# - 使用任务并行库有什么意义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31381384/

相关文章:

c# - 以异步方式启动任务的其他方式

c# - 在实现生产者/消费者模式时使用 Task.Yield 克服 ThreadPool 饥饿

c# - ConfigureAwait(false) 与将同步上下文设置为 null

c# - 删除空文件夹并重新创建后出现 System.IO.DirectoryNotFoundException

c# - 使用 ASP.NET Core 在 Fluent API 中创建由外键组成的复合主键

c# - Task.Factory.StartNew 在部署时不执行任务

c# - 是否有不接受输入但返回输出的 TPL 数据流 block ?

c# - 使用 .NET Core API 上的 Azure AD 对用户进行身份验证?

c# - 在 OrderBy 中维护子序列顺序

c# - 在没有 System.Security.Cryptography 的情况下计算 SHA256 哈希