发布于 2022-05-07 09:45:02
ConcurrentDictionary<TKey,TValue>
集合旨在支持并发场景,其中操作必须是原子的。例如,假设您有一个具有string
键和int
值的字典,并且希望增加键"A"
的值。以下代码不是原子代码:
dictionary["A"]++;
在读取值和更新值之间,另一个线程可能会更改该值,从而导致另一个线程的更改丢失。如果我们像这样重写上面的代码,就会更容易看到它:
var value = dictionary["A"];
value++;
dictionary["A"] = value;
解决方案是避免使用索引器更新字典,而使用TryUpdate
。如果另一个线程拦截了我们的更新,我们将不得不重新开始,直到我们在更新这个键时最终获胜为止:
while (true)
{
var existing = dictionary["A"];
var updated = existing + 1;
if (dictionary.TryUpdate("A", updated, existing)) break;
}
使用while (true)
执行循环(也称为“旋转”)是低锁多线程编程中的一种典型技术。
https://stackoverflow.com/questions/72150934
复制相似问题