在 Parallel.ForEach 中向字典添加值

发布于 2025-01-12 11:33:12 字数 428 浏览 3 评论 0原文

在下面的代码中,我使用 Parallel.ForEach 来获取集合中每个项目的数据并将响应存储在字典中。但是,在字典中,键和值不匹配。第一项的响应,存储在第二项的名称或第三项的名称中。

Dictionary<string, object> keyValues = new Dictionary<string, object>();
Parallel.ForEach(myCollection, item =>
{
    var data = GetData(item);
    if (!keyValues.ContainsKey(item))
    {
        keyValues.Add(item, data);
    }
});
return keyValues;

In the below code am using Parallel.ForEach to get the data of each item in my collection and store the response in the dictionary. But, in the dictionary the key and values are mismatched. Response of 1st item, is stored in the name of 2nd Item or 3rd item name.

Dictionary<string, object> keyValues = new Dictionary<string, object>();
Parallel.ForEach(myCollection, item =>
{
    var data = GetData(item);
    if (!keyValues.ContainsKey(item))
    {
        keyValues.Add(item, data);
    }
});
return keyValues;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烟花肆意 2025-01-19 11:33:12

尝试使用 ConcurrentDictionary,因为 Dictionary 不是线程安全的。

ContainsKeyAdd 方法调用替换为 TryAdd

Try to use ConcurrentDictionary, because Dictionary isn't thread-safe.

Replace the ContainsKey and Add method calls with TryAdd

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文