我有一个列表中的对象列表。该列表可以包含少至一个或多至 500 个条目。我还有一个线程将此列表作为顺序处理这些对象。
为了加快处理速度,我需要将这个列表拆分成多个线程进行并发处理,同时控制同时运行的线程数。
拆分此列表并将较小的列表传递给线程以进行并发处理并控制事件线程总数的最佳方法是什么?
最佳答案
听起来像是使用并行 foreach 循环的完美案例。
根据定义:
The parallel ForEach loop provides a parallel version of the standard, sequential foreach loop. Each iteration processes a single item from a collection. However, the parallel nature of the loop means that multiple iterations may be executing at the same time on different processors or processor cores. This opens up the possibility of synchronisation problems so the loop is ideally suited to processes where each iteration is independent of the others.
看看.NET documentation about Parallel.ForEach和 some examples以便了解其工作原理。
关于C#多线程并发算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35817901/