Parallel.ForEach Misbehaviour [英] Parallel.ForEach Misbehaviour
问题描述
可能重复:结果
的 C#值存储
我在我的控制台应用程序运行今天的一些性能测试和我遇到的东西真是出乎意料跌跌撞撞。我的代码:
I was running some performance tests in my console application today and I stumbled across something really unexpected. My code:
int iterations = 1000000;
var mainList = new List<string>();
for (int i = 0; i < iterations; i++)
{
mainList.Add(i.ToString());
}
var listA = new List<string>();
Parallel.ForEach(mainList, (listItem) =>
{
if (Int32.Parse(listItem)%2 == 0)
{
listA.Add(listItem);
}
});
Console.WriteLine("Parallel Count: {0}", listA.Count);
var listB = new List<string>();
foreach (var listItem in mainList)
{
if (Int32.Parse(listItem) % 2 == 0)
{
listB.Add(listItem);
}
}
Console.WriteLine("Sequential Count: {0}", listB.Count);
这就造成了一个输出:
Which resulted in an output:
并行计数:495939
Parallel Count: 495939
顺序计数1:50万
我跑了几次和并行循环似乎从来没有在次适量得到执行。谁能解释这个不当行为?是并行循环,值得信赖的?
I ran it several times and the parallel loop never seems to get executed at a proper amount of times. Can anyone explain this "misbehaviour"? Are the parallel loops trustworthy?
P.S。我知道有很多废话的代码一样的ToString提供的示例回事()调用上一个整数,比分析他们回来,但那只是一个随机码,我想出了测试时。先谢谢了。
P.S. I know there is a lot of nonsense going on in the provided example of code like ToString() calls on an integer and than parsing them back but that was just a random code I came up with while testing. Thanks in advance.
推荐答案
您的问题是不是与 Parallel.ForEach
。你的问题是与列表与LT; INT>
- 类不是线程安全的。我的猜测是,你正在运行到与列表对象的线程安全问题。尝试使用 ConcurrentBag< INT>
代替,并且将有可能消失的问题。
Your problem is not with Parallel.ForEach
. Your problem is with the List<int>
- the class is not thread safe. My guess is that you are running into thread safety issues with the list object. Try using a ConcurrentBag<int>
instead, and the problem will likely vanish.
从微软有关的线程列表< T>
:
From Microsoft regarding the thread safety of List<T>
:
要允许由多个线程读取和写入访问的集合,您必须实现自己的同步。
To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.
这篇关于Parallel.ForEach Misbehaviour的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!