-1

我想在 C# 中使用并行 For 循环来运行函数并将结果写入变量。

这是我正在使用的当前 for 循环:

string[][,] PatternTables;                    
for (i = 0; i < BOMs.Length; i++)
            {                  
                PatternTables[i] = BOMAnalysis(Pattern, PatternMatch, BOMs, HeaderIndex);
           }

此外,如果有办法做到这一点,那么treads在写入变量之前暂停直到前一个线程完成也会很好地保持事情有序但没有必要。

是的,我现在多次运行同一件事,因为我之前没有做过并行循环,我想在添加变化之前确保一致性。如何将此 for 循环重写为并行 for 循环,以便获得一致的结果?

这是我似乎得到大部分错误的陈述:

if (scrMatch)
    {
        Array.Resize(ref PatternMatch[k][0], PatternMatch[k][0].Length + 1);
        Array.Resize(ref PatternMatch[k][1], PatternMatch[k][1].Length + 1);
        Array.Resize(ref PatternMatch[k][2], PatternMatch[k][2].Length + 1);
        Array.Resize(ref PatternMatch[k][3], PatternMatch[k][3].Length + 1);
        Array.Resize(ref PatternMatch[k][4], PatternMatch[k][4].Length + 1);
        Array.Resize(ref PatternMatch[k][5], PatternMatch[k][5].Length + 1);
        Array.Resize(ref PatternMatch[k][6], PatternMatch[k][6].Length + 1);

        int Row = j + 1;

        PatternMatch[k][0][PatternMatch[k][0].Length - 1] = Row.ToString();
        PatternMatch[k][1][PatternMatch[k][1].Length - 1] = BOMs[i][j, HeaderIndex[4, i]];
        PatternMatch[k][2][PatternMatch[k][2].Length - 1] = BOMs[i][j, HeaderIndex[2, i]];
        PatternMatch[k][3][PatternMatch[k][3].Length - 1] = BOMs[i][j, HeaderIndex[6, i]];
        PatternMatch[k][4][PatternMatch[k][4].Length - 1] = BOMs[i][j, HeaderIndex[3, i]];
        PatternMatch[k][5][PatternMatch[k][5].Length - 1] = BOMs[i][j, HeaderIndex[0, i]];
        PatternMatch[k][6][PatternMatch[k][6].Length - 1] = BOMs[i][j, HeaderIndex[1, i]];


    }
4

2 回答 2

1

看看 Parallel.For() 方法。
您使用 Parallel.For()-Method 的代码应如下所示:

        string[][,] PatternTables;
        Parallel.For(0, PatternTables.Length,
            index =>
            {
                PatternTables[index] = BOMAnalysis(Pattern, PatternMatch, BOMs, HeaderIndex);
            });

参数:

  1. 开始索引
  2. 最后索引
  3. 委托(每次迭代执行的代码)
    看看这个:https ://msdn.microsoft.com/de-de/library/dd460713(v=vs.110).aspx
于 2017-10-19T18:13:32.347 回答
0

To make it thread safe you would have to use a Lock.

Dim locker as new Object();
Parallel.For(0, BMOs.length, index =>{

   lock(locker){
     //thread safe code
   }

 });

If the whole function that you have in the for loop needs to be locked then the regular loop you are using now will work fine. This is because the lock will only allow one thread to access that function at a time, defeating the purpose of the parallel loop.

于 2017-10-19T18:15:09.370 回答