我做了这个小程序来测试并行化。
当我多次点击 button1 时,它以 IndexOutOfBounds 异常结束。我想这是因为我的内存不足。为什么我通过并行化而不是常规的 foreach(button2 click)得到这个?
private void button1_Click(object sender, EventArgs e)
{
var s = Stopwatch.StartNew();
int[] nums = new int[10000];
List<int> randoms = new List<int>();
Parallel.ForEach(nums, i =>
{
randoms.Add(new Random().Next());
});
s.Stop();
label1.Text = "Added " + randoms.Count() + " randoms in "
+ s.Elapsed.Milliseconds.ToString() + " milliseconds";
}
private void button2_Click(object sender, EventArgs e)
{
var s = Stopwatch.StartNew();
int[] nums = new int[10000];
List<int> randoms = new List<int>();
foreach (var i in nums)
{
randoms.Add(new Random().Next());
}
s.Stop();
label2.Text = "Added " + randoms.Count() + " randoms in "
+ s.Elapsed.Milliseconds.ToString() + " milliseconds";
}