【发布时间】:2020-10-18 07:09:00
【问题描述】:
我需要并行执行一些流程,但主要关注的是,我正在将参数传递给该流程
。
该流程有两个子任务 =>
- 调用 API 2.将来自 API 的响应保存到 DB
//calling in this function ProcessData(arguments....., shopKey, offSet);
private void GetMoreData(some arguments) { //calling in 2-3 times Parallel
Monitor.Enter(_object);
long ? maxSearchResults = 0;
string shopKey = string.Empty;
long ? offSet = 0;
long ? pageSize = 200;
try {
List < Action > delegates = new List < Action > ();
if (maxSearchResults != null) {
double value = double.Parse((maxSearchResults / pageSize).ToString());
iteratorLength = int.Parse(Math.Round(value, MidpointRounding.AwayFromZero).ToString());
//some logic to to get no of times we need to call loops
for (int iterator = 0; iterator < iteratorLength; iterator++) {
offSet = offSet + 1;
delegates.Add(() = >{
ProcessData(arguments....., shopKey, offSet);
});
}
}
Parallel.Invoke(delegates.ToArray());
}
catch(Exception ex) {
//throw new Exception....
}
finally {
Monitor.Exit(_object);
}
}
在上面的例子中,如果我们调用了 5 个循环,
但是当我调试委托数组时,我发现如下所示
GetMoreData(参数....., same_shopKey, offSet:5);
GetMoreData(参数....., same_shopKey, offSet:5);
GetMoreData(参数....., same_shopKey, offSet:5);
GetMoreData(arguments....., same_shopKey, offSet:5);
代表应该这样工作(我想实现这个)==>
GetMoreData(参数....., same_shopKey, offSet:2);
GetMoreData(参数....., same_shopKey, offSet:3);
GetMoreData(参数....., same_shopKey, offSet:4);
GetMoreData(arguments....., same_shopKey, offSet:5);
【问题讨论】:
-
new List < Action > ()- 你有一些非常奇怪的间距... -
您是否考虑过使用
Partitioner,而不是手动进行分区?你可以这样使用它:Parallel.ForEach(Partitioner.Create(0, maxSearchResults, pageSize), range => {...
标签: c# parallel-processing parameter-passing