[英]Run any number of functions, each on their own thread
What is the most efficient way of performing the same function on a collection of objects, each running in parallel? 在对象集合上执行相同功能的最有效方法是什么,每个对象并行运行? I know I could just do new Thread(() => MyFunc(myParam)).Start()
in a loop, but is there a better way? 我知道我可以做一个new Thread(() => MyFunc(myParam)).Start()
循环中的new Thread(() => MyFunc(myParam)).Start()
,但是有更好的方法吗? This seems like a very ugly way of doing it. 这似乎是一种非常丑陋的方式。
[...] is there a better way? [...] 有没有更好的办法? This seems like a very ugly way of doing it. 这似乎是一种非常丑陋的方式。
Yes, that is a very ugly and inefficient way of doing it. 是的,这是一种非常难看和低效的方式。 Each thread will consume a lot of resources but your computer can only execute N threads at the same time where N is the number of CPU cores on your computer. 每个线程将消耗大量资源,但您的计算机只能在N是计算机上的CPU核心数的同时执行N个线程。 So instead of using a low-level primitive like a thread you can build on top of libraries that optimize the number of threads to fit the number of CPU cores. 因此,不是使用像线程这样的低级原语,而是可以构建在库之上,优化线程数以适应CPU核心数。
In your case where you have a collection of objects I suggest: 如果您有一组对象,我建议:
LINQ code: LINQ代码:
var result = source.Select(item => ...).ToList();
Parallel LINQ code: 并行LINQ代码:
var result = source.AsParallel().Select(item => ...).ToList();
For each loop: 对于每个循环:
foreach (var item in source)
Process(item);
Parallel for each loop: 每个循环并行:
Parallel.ForEach(
source,
item => Process(item);
);
For loop: 对于循环:
for (var i = 0; i < list.Count; i += 1)
list[i] = Process(list[i]);
Parallel for loop: 并行循环:
Parallel.For(
0,
list.Count,
i => {
list[i] = Process(list[i]);
}
);
You can use Parallel.For
or Parallel.Foreach
or Parallel.Invoke
starting from .net 4.0. 您可以从.net 4.0开始使用Parallel.For
或Parallel.Foreach
或Parallel.Invoke
。
There is very little reason to use Thread
directly in your code starting from .Net4.0. 没有理由直接在.Net4.0开始的代码中使用Thread
。 You can use TPL which is recommended way of achieving Task parallelism or Data parallelism. 您可以使用TPL,这是实现任务并行或数据并行的推荐方法。
To quote Stephen Cleary from his book 引用Stephen Cleary 的书
As soon as you type
new Thread()
, it's over; 一旦你键入new Thread()
,它就结束了; your project already has legacy code 您的项目已有遗留代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.