gpt4 book ai didi

c# - 如果源为空,Parallel.ForEach 是否启动线程?

转载 作者:太空狗 更新时间:2023-10-29 22:21:19 25 4
gpt4 key购买 nike

我以这种方式使用 Parallel.ForEach:

public void myMethod(IEnumerable<MyType> paramIeCollection)
{
Parallel.Foreach(paramIeCollection,
(iterator) =>
{
//Do something
});
}

我想知道当 paramIeCollection 为空时,Parallel.ForEach 无论如何都会启动并从线程池中获取线程并消耗资源,或者它是否首先检查是否有项目在集合中。

如果它不检查,为了避免这种情况,我在这段代码中考虑:

if(paramIeCollection.count > 0)
{
//run Parallel.Foreach
}

所以问题是,在调用 Parallel.ForEach 之前检查集合是否有项是一个好习惯,还是不需要?

最佳答案

说实话,它确实会检查。但是,如果您查看源代码,它会在弄清楚之前进行一些其他检查和平衡

如果您有处理器指令强制症,像if(list.count > 0) 这样的简单事先检查可能会为您节省大量 IL。然而在现实世界中它不会有太大的不同

System.Threading.Tasks Reference Source

例如,对于简单的 IEnumerable 重载,您可以通过 E.g 跟踪源代码

public static ParallelLoopResult ForEach<TSource>(IEnumerable<TSource> source, Action<TSource> body)

电话 ForEachWorker

private static ParallelLoopResult ForEachWorker<TSource, TLocal>(
IEnumerable<TSource> source,
ParallelOptions parallelOptions,
Action<TSource> body,
Action<TSource, ParallelLoopState> bodyWithState,
Action<TSource, ParallelLoopState, long> bodyWithStateAndIndex,
Func<TSource, ParallelLoopState, TLocal, TLocal> bodyWithStateAndLocal,
Func<TSource, ParallelLoopState, long, TLocal, TLocal> bodyWithEverything,
Func<TLocal> localInit, Action<TLocal> localFinally)

内联电话

// This is an honest-to-goodness IEnumerable.  Wrap it in a Partitioner and defer to our
// ForEach(Partitioner) logic.
return PartitionerForEachWorker<TSource, TLocal>(Partitioner.Create(source), parallelOptions, body, bodyWithState,
bodyWithStateAndIndex, bodyWithStateAndLocal, bodyWithEverything, localInit, localFinally);

PartitionerForEachWorker

// Main worker method for Parallel.ForEach() calls w/ Partitioners.
private static ParallelLoopResult PartitionerForEachWorker<TSource, TLocal>(
Partitioner<TSource> source, // Might be OrderablePartitioner
ParallelOptions parallelOptions,
Action<TSource> simpleBody,
Action<TSource, ParallelLoopState> bodyWithState,
Action<TSource, ParallelLoopState, long> bodyWithStateAndIndex,
Func<TSource, ParallelLoopState, TLocal, TLocal> bodyWithStateAndLocal,
Func<TSource, ParallelLoopState, long, TLocal, TLocal> bodyWithEverything,
Func<TLocal> localInit,
Action<TLocal> localFinally)

最终由谁来检查

while (myPartition.MoveNext())

关于c# - 如果源为空,Parallel.ForEach 是否启动线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48746188/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com