?它是安全和正确的,在并行内部。对于每个并行包,添加和读取?
示例(在VB.net中(:
Dim myConcurrentBag As New ConcurrentBag(Of myClass)
Parallel.ForEach(elementList, Sub(element)
Try
Dim newObject as New myClass
newObject.Property1 = element.PropertyX
' Check if item is inserted inside myConcurrentBag
' ¿IS THIS LINE CORRECT?
If (myConcurrentBag.Select(Function(x) x.Property1).Contains(newObject.Property1)) Then
Return
End If
myConcurrentBag.Add(newObject)
Catch ex As Exception
' Log exception
End Try
End Sub)
最后,这是最好的方法,对吧:
Dim myConcurrentDictionary As New ConcurrentDictionary(Of String, myClass)
Parallel.ForEach(elementList, Sub(element)
Try
Dim newObject as New myClass
newObject.Property1 = element.PropertyX
' Check if item is inserted inside myConcurrentDictionary
' ¿IS THIS LINE CORRECT?
If (myConcurrentDictionary.ContainsKey(newObject.Property1)) Then
Return
End If
myConcurrentDictionary.TryAdd(newObject.Property1, newObject)
Catch ex As Exception
' Log exception
End Try
End Sub)
我知道您的意图是在Parallel.ForEach的执行完成后,在PropertyX方面拥有唯一的项。
由于ConcurrentBag的枚举在内容的时间点快照上运行,另一个任务可能会插入具有相同属性值的对象,而Select((不会看到这个新对象,因此将无法满足唯一性要求。
也请检查这个问题——在枚举期间添加和删除ConcurrentBag的元素