并行处理,内部循环,我们可以访问并行度吗? [英] Parallel Processing, inside loop, can we access the Degree of Parallelism?
问题描述
在以下循环中,我想添加逻辑以说明处理器1是否执行此操作,如果处理器2如此执行,等等.我一直在尝试各种属性,例如...
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());
...但是我看到线程ID越来越多,所以它的线程到处理器的线程很多.那么如何在循环中获得1-4?我刚得到相同值的DomainID
...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) => { });
我的问题是我希望它能够将列表中的记录分为4组,并且处理1处理前25%,依此类推.
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.
推荐答案
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];
}
});
当您要将任务分为4组时,只需一个适当的超载:
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);
这篇关于并行处理,内部循环,我们可以访问并行度吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!