繁体   English   中英

Parallel.ForEach 添加和读取 ConcurrentBag,是否安全?

[英]Parallel.ForEach add and read ConcurrentBag, is safe?

¿它是安全和正确的,在parallel.foreach 中,添加和读取并发包?

示例(在 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 的元素

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM