Skip to main content
 首页 » 编程设计

c#之parallel.foreach 和字典集合

2024年06月03日83sharpest

我不明白我的代码是怎么出错的这里是一段代码:

var filter=new dictionary<string,dictionary<string,bool>>(); 
//data here is of type dictionary<string,bool> 
Parallel.Foreach(data,t=> 
{ 
 var filter1=data.Where(p=>p.Value).ToDictionary(p=>p.Key,p=>p.Value); 
 filter.Add(t.key,filter1); 
}); 

有时,最终过滤器中有一个空键,如果我使用简单的 for 循环,这种情况就不会发生。

请您参考如下方法:

[this] has never happened if I had used a simple for loop.

问题是您同时添加到filter。您可以使用 AsParallel() 解决此问题:

var filter = data.AsParallel().ToDictionary(t => 
    t.Key 
,   data.Where(p=>p.Value).ToDictionary(p=>p.Key, p=>p.Value) 
);