gpt4 book ai didi

c# - 更改 ConcurrentBag 中的对象?

转载 作者:太空宇宙 更新时间:2023-11-03 21:20:24 26 4
gpt4 key购买 nike

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

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

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.

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

关于c# - 更改 ConcurrentBag 中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31195881/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com