Skip to main content
 首页 » 编程设计

c#之更改 ConcurrentBag 中的对象

2024年02月06日12虾米哥

我读到要修改或改变并发包中的对象,我必须将其取出、修改,然后再放回去。

但是,我看到了执行以下操作的代码:

var obj = bag.FirstOrDefault(report => report.id == id); 
obj.name = 'Change to something else'; 

其中 Report 是包中包含的对象类型。

现在这似乎奏效了。这是正确的吗?

请您参考如下方法:

它可以工作,但它不是线程安全的。查看docs :

All public and protected members of ConcurrentBag<T> are thread-safe and may be used concurrently from multiple threads. However, members accessed through one of the interfaces the ConcurrentBag<T> implements, including extension methods, are not guaranteed to be thread safe and may need to be synchronized by the caller.

换句话说,为了以线程安全的方式修改或改变并发包中的对象,您必须将其取出、修改,然后再放回。