0

经过昨天的大量谷歌搜索后,我发布了这个问题

我正在研究多线程并且我正在使用 Parrallel.For,我想知道我们如何在 Parrallel.for 中使用 for 循环。据我所知,这不是最佳做法,但现在我必须为我的 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
  }

但问题是内部 for 循环不等待,它与多线程值重叠(当 parrallel.for 迭代时)我尝试使用 lock 但没有用。

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

4

1 回答 1

1

您已经在方法之外声明了变量startend因此所有线程将共享相同的变量。将它们设置为方法的本地,以便线程拥有自己的一组变量:

int start = (i * dataPerBatch) + 1;
int end = dataPerBatch * (i + 1);
于 2014-10-01T10:51:14.397 回答