Skip to main content
 首页 » 编程设计

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

2024年02月06日13cloudgamer

我有一台四核 PC。

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

现在,我在 Code Project 上找到另一篇赞美这个库的文章。

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

谢谢

请您参考如下方法:

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

根据 MSDN Parallel Processing and Concurrency in the .NET Framework在 .NET 中基本上可以通过三种方式进行并行处理:

  1. 托管线程,您自己处理线程及其同步。
  2. 各种异步编程模式。
  3. .NET Framework 中的并行编程,Task Parallel Library 和 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.