Parallel Processing, inside loop, can we access the Degree of Parallelism?

删除回忆录丶 提交于 2019-12-11 04:24:40

问题


In the following loop, I want to add logic to say if processor 1 then do this, if processor 2 do that etc. I have been trying various properties like ...

Console.WriteLine("Domain ID = " + Thread.GetDomainID().ToString());
Console.WriteLine("Thread ID = " + Thread.CurrentThread.ManagedThreadId.ToString());

...but i see thread ID is counting up and up so its the thread where many threads to a processor. So how to get the 1-4 inside the loop? The DomainID I just get the same value

Parallel.ForEach(list.OrderBy(n => n.ScheduledBillingId),
    new ParallelOptions { MaxDegreeOfParallelism = 4  }, (item) => { });

My issue is I want this to be able to split the records in the list into 4 groups and process 1 deals with the first 25% and so on.


回答1:


For your job and Parallel.ForEach you can use a partitioner for your list, like this:

// Partition the entire source array.
var rangePartitioner = Partitioner.Create(0, list.Count);

After that you simply provide that partitioner for your loop:

Parallel.ForEach(rangePartitioner, (range, loopState) =>
{
    // Loop over each range element without a delegate invocation.
    for (var i = range.Item1; i < range.Item2; ++i)
    {
        var taskToRun = list[i];
    }
});

As you want to split your tasks by 4 groups, you just need a proper overload:

var rangePartitioner = Partitioner.Create(0, source.Length, source.Length / 4);


来源:https://stackoverflow.com/questions/43316167/parallel-processing-inside-loop-can-we-access-the-degree-of-parallelism

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!