我有以下方法:
现在我像这样在for循环中调用它:
在场景1中,输出结果为:
在场景2中,输出结果为:
我有以下方法:
static Random rr = new Random();
static void DoAction(Action a)
{
ThreadPool.QueueUserWorkItem(par =>
{
Thread.Sleep(rr.Next(200));
a.Invoke();
});
}
现在我像这样在for循环中调用它:
for (int i = 0; i < 10; i++)
{
var x = i;
DoAction(() =>
{
Console.WriteLine(i); // scenario 1
//Console.WriteLine(x); // scenario 2
});
}
在场景1中,输出结果为:
10 10 10 10 ... 10
在场景2中,输出结果为:
2 6 5 8 4 ... 0
(0到9的随机排列)
你如何解释这个问题?C#不应该为匿名委托调用保留变量(这里是i
)吗?