Parallel.For VS For。为什么会有这种差异?

时间:2012-01-10 15:03:17

标签: vb.net parallel-processing

我有一个数组(i),我想根据i值和Parallel.For()进行一些数学计算。

但问题是,在运行Parallel.For()之后,我的数组上的值仍为0.

当我的for为0到0时会发生这种情况。

这是我的代码:

    Dim a(10) As Double
    Parallel.For(0, 0, Sub(i)
                           a(i) = i + 2
                           'There is some calculations based on instead of previous line!
                           'But anyway, the result will be on a(i).
                       End Sub)

    MessageBox.Show(a(0)) 'This returns 0!


    For i As Integer = 0 To 0
        a(i) = i + 2
    Next
    MessageBox.Show(a(0)) 'But this returns 2!

有什么问题?

2 个答案:

答案 0 :(得分:4)

来自Microsoft's documentation

如果fromInclusive大于或等于toExclusive,则该方法立即返回而不执行任何迭代。

因此,当您使用Parallel.For(0,0,etc)时,不会发生任何事情。

尝试Parallel.For(0,1),看看你是否得到了结果。

答案 1 :(得分:1)

您的正确代码应如下所示

   Dim a(10) As Double
    Parallel.For(0, 1, Sub(i)
                           a(i) = i + 2
                           'There is some calculations based on instead of previous line!
                           'But anyway, the result will be on a(i).
                       End Sub)

    MessageBox.Show(a(0)) '2!


    For i As Integer = 0 To 0
        a(i) = i + 2
    Next
    MessageBox.Show(a(0)) '2