2014-10-01 56 views
0

环路很多从谷歌上搜索昨天之后我张贴了这个问题对于里面的Parallel.For

我对多线程工作,我使用Parrallel.For,我想知道我们如何使用内循环Parrallel。对于。至于我读这是不是最好的做法,但现在我有我的RND工作

 int dataPerBatch = 100; 
ParallelLoopResult result = Parallel.For(0, totalLoops, (i) => UpdateRecords(i, lstVins)); 

public void UpdateRecords(int i, List<string> lst) 
    { 

     start = (i * dataPerBatch) + 1; 
     end = dataPerBatch * (i + 1); 
    //Inner For Loop 
    for (int j = start; j <= end; j++) 
     { 
      // Call individual list object to web-api and fetch the result in new list object 

      // Here the start and end value keep on chahnging 
     } 

     // Call this collection again to the web- api and do bulk update 
    } 

做的,但问题是内部的循环不等待,它在与穆蒂线程值圈(当parrallel.for迭代)我已经尝试使用锁,但没用。

请注意:我没有粘贴整个代码只是骨架

+0

是'start'和'end'内'UpdateRecords'定义或共享所有并行循环? – DavidG 2014-10-01 10:48:22

+0

为什么要麻烦? Parallel.For()已经批量生成,你试图变得太聪明。 – 2014-10-01 11:12:25

回答

1

你声明的变量startend的方法之外,因此所有的线程将共享相同的变量。让他们本地的方法,这样的线程有自己的一套变量:

int start = (i * dataPerBatch) + 1; 
int end = dataPerBatch * (i + 1); 
+0

这就是为什么我在评论中提问的原因... – DavidG 2014-10-01 10:53:39