Parallel.ForEach local storage
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 Nothin开发者_运维问答g 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:
Thread 1: results = model.Execute ' results are from Thread1's current modelEngine
Thread 2: results = model.Execute ' results are from Thread2's current modelEngine
Thread 2: If results IsNot Nothing Then ' results are from Thread2's current modelEngine
Thread 1: If results IsNot Nothing Then ' results are from Thread2's current modelEngine(!)
Just move it inside, I don't see why you'd want to declare it outside the loop anyways.
精彩评论