限制并行执行的方法

时间:2018-09-06 18:14:55

标签: c# task-parallel-library

在节流并行执行时,以下两种方法有什么区别?还是优先于另一个?

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)));
}

此处介绍了第二种方法:https://blogs.msdn.microsoft.com/andrewarnottms/2017/05/11/limiting-concurrency-for-faster-and-more-responsive-apps/

0 个答案:

没有答案