Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# parallel.foreach和字典集合_C#_Parallel.foreach - Fatal编程技术网

C# parallel.foreach和字典集合

C# parallel.foreach和字典集合,c#,parallel.foreach,C#,Parallel.foreach,我不明白我的代码是怎么出错的这是一段代码: 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

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

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);
});
var filter=newdictionary();
//这里的数据是字典类型
Parallel.Foreach(数据,t=>
{
var filter1=data.Where(p=>p.Value).ToDictionary(p=>p.Key,p=>p.Value);
filter.Add(t.key,filter1);
});
有时,最后一个过滤器中有一个空键,如果我使用了一个简单的for循环,这是从来没有发生过的

如果我使用了一个简单的for循环,就不会发生这种情况

问题是您同时添加到
过滤器
。您可以使用
aspallel()
修复此问题:


谢谢,这是可行的,但是你能告诉我为什么这个方法会这样做吗?即使我同时添加数据,数据中也没有空键,那么并行类如何创建一些不应该有空键的虚拟任务呢existed@JokingBear当同时修改字典时,其内部数据结构将无效,尤其是当水桶重新平衡时。并发更新相互写入数据,因此键和/或值出现
null
,即使非
null
项已提供给
Add
方法。事实上,在不触发异常的情况下,您不能合法地将
null
键传递给字典。
var filter = data.AsParallel().ToDictionary(t =>
    t.Key
,   data.Where(p=>p.Value).ToDictionary(p=>p.Key, p=>p.Value)
);