I recently changed a For Each loop to a Parallel.ForEach loop. I’m concerned about an object being declared outside the loop but assigned while iterating in the loop. Here is the simplified code.
Dim results As ModelResults
Dim noResultsModel As New List(Of ModelResults)
Dim lock As New Object
Parallel.ForEach(_modelEngines,
Sub(model)
results = model.Execute
If results IsNot Nothing Then
SyncLock lock
noResultsModel.Add(results)
End SyncLock
End If
results = Nothing
End Sub)
Is there a potential race condition with the results object? Would anything be different if I moved the declaration of results into the for loop?
Yes, there definitely is a race condition with the variable declared outside the loop:
Just move it inside, I don’t see why you’d want to declare it outside the loop anyways.