为什么在 ParallelLoopState 类中看不到 CurrentIteration

kev*_*vin 2 .net c# task-parallel-library parallel.foreach

当我调试时Parallel.ForEach,我可以发现有字段CurrentIteration,但我找不到它ParallelLoopState

截图1

截图2

如何获取CurrentIteration的值?

Gur*_*ron 5

ParallelLoopState不公开公开此成员,您可以使用Parallel.ForEach接受的重载Action<TSource,ParallelLoopState,Int64>

它提供以下参数:当前元素ParallelLoopState当前元素的索引(an Int64)。

Parallel.ForEach(collection, (el, _, index) => ...);
Run Code Online (Sandbox Code Playgroud)

另一种选择是使用Parallel.For(如果源集合允许通过索引访问):

Parallel.ForEach(collection, (el, _, index) => ...);
Run Code Online (Sandbox Code Playgroud)