这里发生了一件奇怪的事。我以为Parallel.Foreach会等到它的所有任务完成后才能继续工作。但是,我有这样的事情:
List<string> foo(List<A> list){
Dictionary<string, bool> dictionary = new Dictionary<string, bool>();
Parallel.Foreach(list, element =>
{
dictionary[element.Id] = true;
if (element.SomeMethod()){
dictionary[element.Id] = false;
}
});
List<string> selectedIds = (from element in list where !dictionary[element.Id] select element.Id).ToList();
return selectedIds;
}
然后,我在select行中得到System.Collections.Generic.KeyNotFoundException (有时,并不总是)。如您所见,我正在为每个可能的键(列表元素的Ids)初始化字典,然后得到此异常,这使我认为在Parallel.Foreach执行完成之前可能会到达这一行.是那么回事吗?如果是这样的话,我如何等待直到这个Parallel.Foreach的所有分支完成?
发布于 2015-02-12 17:01:25
Parallel.Foreach
不需要等待,因为它不返回Task
,也不是异步的。当对该方法的调用完成时,迭代已经完成。
但是,Parallel.Foreach
同时使用多个线程,而Dictionary
并不是线程安全的。
您可能有一个竞争条件,您应该使用线程安全的ConcurrentDictionary
。
使用PLinq的AsParallel
可以更简单地解决这一特殊情况
list.AsParallel().Where(element => !element.SomeMethod());
https://stackoverflow.com/questions/28483237
复制相似问题