I have a snippet of code that I thought would work because of closures; however, the result proves otherwise. What is going on here for it to not produce the expected output (one of each word)?
Code:
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())
Output:
other
other
other
This has to do with the fact that closures capture the variable itself without evaluating it until it’s actually used. After the end of the foreach loop the value of
textis "other", and it as after the loop ends that the method is invoked, and at the time of invocation the value of the captured variabletextis "other"See this blog post from Eric Lippert for details. He explains the behavior and some of the reasons behind it.