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

I have a piece of code that I thought would work due to closure; however, the result is the opposite. What happens here so as not to produce the expected result (one from each word)?

the 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())

Conclusion:

other
other
other
+5
source share
6 answers

This is because closures fix this variable without evaluating it before actual use. After the end of the foreach loop, the value textis "different", and after the loop ends, the method terminates, and during the call, the value of the captured variable textis "different",

. . .

+7

. for, foreach: . - , ( ). , "" .

: 1, 2.

- :

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

testThreads.ForEach(t => t.Start())

, "" copy. - text. , .

+4

# . foreach , text .

:

string[] source = new string[] {"this", "that", "other"};
List<Thread> testThreads = new List<Thread>();

foreach (string text in source)
{
    // Capture the text before using it in a closure
    string capturedText = text;

    testThreads.Add(new Thread(() =>
        {
            Console.WriteLine(capturedText);
        }));
}

testThreads.ForEach(t => t.Start());

, "" text for. , , .

+2

, , , , - "", , , . :

string[] source = new string[] {"this", "that", "other"};
foreach (string text in source)
{
    new Thread(t => Console.WriteLine(t)).Start(text);
}
0

, .

, :

foreach (string text in source)
{
    string textLocal = text; // this is all you need to add
    testThreads.Add(new Thread(() =>
    {
        Console.WriteLine(textLocal); // well, and change this line
    }));
}
0

/lambdas foreach loop counter. ( foreach counter), .

0

All Articles