2014-10-01 27 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