C#中的奇数(循环/线程/字符串/ lambda)行为

Que*_*mer 5 c# multithreading closures loops

我有一段代码,我认为因为封闭而可以工作; 但是,结果证明不是这样.这里发生了什么不能产生预期的输出(每个单词之一)?

码:

string[] source = new string[] {"this", "that", "other"};
List<Thread> testThreads = new List<Thread>();
foreach (string text in source)
{
    testThreads.Add(new Thread(() =>
    {
        Console.WriteLine(text);
    }));
}

testThreads.ForEach(t => t.Start())
Run Code Online (Sandbox Code Playgroud)

输出:

other
other
other
Run Code Online (Sandbox Code Playgroud)

Dav*_*vy8 7

这与闭包捕获变量本身而不进行评估直到它实际使用的事实有关.在foreach循环结束后,值为text"other",并且在循环结束后调用该方法,并且在调用时,捕获的变量的text值为"other"

有关详细信息,请参阅Eric Lippert的此博客文章.他解释了行为及其背后的一些原因.