以下多线程程序在VS 2017中引发并超出范围索引异常,但我找不到任何超出范围的索引:
using System;
using System.Threading;
class Program
{
const int n = 100;
static int[] sum = new int[n];
static void f(int i, int x)
{
sum[i] = x; // Index was outside the bounds of the array.
}
static void Main()
{
Thread[] t = new Thread[n];
for (int i = 0; i < n; i++)
{
if (i >= 100)
throw null;
t[i] = new Thread(() => f(i,i+1));
t[i].Start();
}
int summ = 0;
for (int i = 0; i < n; i++)
{
t[i].Join();
summ += sum[i];
}
Console.WriteLine(summ);
Console.ReadKey();
}
}
怎么了?