static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
Thread t = new Thread(delegate()
{
Thread.Sleep(new Random().Next(1, 10000));
Console.Write(i + ", ");
});
t.Start();
}
}
将得到输出:10, 10, 10, 10, 10, 10, 10, 10, 10, 10,而不是我们期望的类似于:3, 5, 6, 1, 0, 7, 9, 8, 4, 2, 这样的输出。这是为什么呢?(在实际 项目中出现这个Bug的代码请参考[1])分析:使用Reflector查看编译之后的代码下面是编译前后的代码对比。(使用Reflector的具体方法请参考[2],这里仅展现结果)