在 Parallel.ForEach 中向字典添加值
在下面的代码中,我使用 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试使用 ConcurrentDictionary,因为
Dictionary
不是线程安全的。将
ContainsKey
和Add
方法调用替换为TryAdd
Try to use ConcurrentDictionary, because
Dictionary
isn't thread-safe.Replace the
ContainsKey
andAdd
method calls withTryAdd