1
我最近將For Each循環更改爲Parallel.ForEach循環。我擔心一個對象在循環外部被聲明,但是在循環中迭代時被賦值。這是簡化的代碼。Parallel.ForEach本地存儲
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)
是否存在與結果對象的潛在競爭條件?如果我將結果聲明移至for循環,會不會有所不同?