for (int i = 1; i < 100; i++) { ThreadPool.QueueUserWorkItem((o) => { int z = i; Thread.Sleep(1000); Console.Write(z.ToString()); Console.Write(Environment.NewLine); }); }
为啥输出的都是100呢,,不是用z保存了变量了吗
收到一只叮咚
浏览 364回答 9
9回答
隔江千里
for (int i = 1; i < 100; i++) { ThreadPool.QueueUserWorkItem((o) => { int z = (int)o; Thread.Sleep(1000); Console.Write(z.ToString()); Console.Write(Environment.NewLine); },i); }
老兄位置放错啦!~
看我这个吧:
for (int i = 1; i < 100; i++)
{
ThreadPool.QueueUserWorkItem(start =>
{
int z = i;
Console.WriteLine(z.ToString());
});
Thread.Sleep(1);//在循环中需要调用一下,由于被置于ThreadPool中的操作是异步,所以还没有来的执行,z就被for循环改变,永远是100
}