为什么在ParallelLoopState类中看不到CurrentIteration

问题描述 投票:0回答:2

当我调试

Parallel.ForEach
时,我可以发现有字段
CurrentIteration
,但我在
ParallelLoopState
中找不到它。

如何获取CurrentIteration的值?

c# .net task-parallel-library parallel.foreach
2个回答
1
投票

此属性不是

public
。如果您对当前迭代感兴趣,唯一的选择是将其作为数据的一部分传递:

var indexedSource = source.Select((item, index) => (item, index));

Parallel.ForEach(indexedSource, parallelOptions, entry =>
{
    var (item, index) = entry;
    // Process the item, that has this index.
});

在上面的示例中,我使用了

Select
LINQ 运算符,其
selector
类型为
Func<TSource, int, TResult>


1
投票

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

重载

它提供以下参数:当前元素、

ParallelLoopState
当前元素的索引
Int64
)。

Parallel.ForEach(collection, (el, _, index) => ...);

另一个选项是使用

Parallel.For
(如果源集合允许通过索引访问):

Parallel.For(0, collection.Length, index =>
{
    var current = collection[index];
});
© www.soinside.com 2019 - 2024. All rights reserved.