gpt4 book ai didi

c# - 字典更新线程安全

转载 作者:太空狗 更新时间:2023-10-30 00:41:36 27 4
gpt4 key购买 nike

下面的代码线程安全吗?

var dict = new Dictionary<int, string>()
{ { 0, "" }, { 1, "" }, { 2, "" }, { 3, "" } };

var nums = dict.Keys.ToList();

Parallel.ForEach(nums, num =>
{
dict[num] = LongTaskToGenerateString();
});

return dict;

最佳答案

不,Dictionary<TKey, TValue>类对于修改不是线程安全的,如 documentation 中所示:

A Dictionary<TKey, TValue> can support multiple readers concurrently, as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with write accesses, the collection must be locked during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

在您的情况下,如果某些线程将完成 LongTaskToGenerateString他们的词典更新几乎同时会受到干扰。

您可以使用 SyncRoot 属性手动同步访问,或者只使用 ConcurrentDictionary<TKey, TValue> 类,如 asawyer 所建议在评论中。

This实现表明,如果您只是更新现有键的值,应该 没问题(同时查看 this )- 不优雅的效果可能是 version 的不准确值属性(property)。它用于防止在枚举时修改集合,因此它最终的值并不重要。不过不知道有什么保证。

关于c# - 字典更新线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19686557/

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