Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odd (loop / thread / string / lambda) behavior in C#

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
like image 304
QueueHammer Avatar asked Jul 01 '10 18:07

QueueHammer


1 Answers

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 text is "other", and it as after the loop ends that the method is invoked, and at the time of invocation the value of the captured variable text is "other"

See this blog post from Eric Lippert for details. He explains the behavior and some of the reasons behind it.

like image 128
Davy8 Avatar answered Oct 01 '22 06:10

Davy8