在节流并行执行时,以下两种方法有什么区别?还是优先于另一个?
var parallelOptions = new ParallelOptions() {MaxDegreeOfParallelism = 4};
Parallel.ForEach(collection, parallelOptions, item =>
{
// ...
});
和
Task ThrottleParallelWorkAsync(IEnumerable<T> data, Action<T> worker)
{
TaskScheduler scheduler = new ConcurrentExclusiveSchedulerPair(
TaskScheduler.Default, // schedule work to the ThreadPool
Environment.ProcessorCount * 2) // Schedule enough to keep all threads busy, with a queue to quickly replace completed work
.ConcurrentScheduler; // We only use the concurrent member of this scheduler "pair".
return Task.WhenAll(
data.Select(v => Task.Factory.StartNew(() => worker(v), CancellationToken.None, TaskCreationOptions.None, scheduler)));
}