I've run across something very weird and I don't understand whats going on. I thought I understood how assignment works in VB, but apparently not. I know that when dealing with parallel for loops, as I am, you have to be careful about things though. I've made two small pieces of code with one difference that show my question. In the first piece of code, I declare an array, and by default it is populated with zeros. The parallel for loop does nothing to modify the original array. Then the array of zeros is output to the console for the user to see. In the second piece of code, I try to import the declared array into the loop and assign the values to a new array. But here's where it gets weird. The output of the code is the values of the array I declared inside the loop, but without ever assigning those values to the original array. Can someone please help me make some sense of this!?! Thanks.
Output of 1st Code:
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
Output of 2nd Code:
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100
Code:
Module Module1
Sub Main()
Dim values(9, 1) As Integer
'In this piece of code, the loop does nothing to the "values" array
System.Threading.Tasks.Parallel.For(0, values.GetLength(0), Sub(i)
Dim ValTemp(9, 1) As Integer '<--- Only difference between codes
ValTemp(i, 0) = i + 1
ValTemp(i, 1) = (i + 1) * (i + 1)
End Sub)
'Output the values array to the console
For row = 0 To 9
Console.WriteLine("{0} {1}", values(row, 0), values(row, 1))
Next
End Sub
End Module
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
Code:
Module Module1
Sub Main()
Dim values(9, 1) As Integer
'In this piece of code, the loop somehow modifies the "values" array
System.Threading.Tasks.Parallel.For(0, values.GetLength(0), Sub(i)
Dim ValTemp(,) As Integer = values '<--- Only difference between codes
ValTemp(i, 0) = i + 1
ValTemp(i, 1) = (i + 1) * (i + 1)
End Sub)
'Output the values array to the console
For row = 0 To 9
Console.WriteLine("{0} {1}", values(row, 0), values(row, 1))
Next
End Sub
End Module
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100