As for the local variable passing in the stream

I find it difficult to understand the unexpected output for the following program:

class ThreadTest
{
     static void Main()
     {
          for(int i = 0; i < 10; i++)
               new Thread(() => Console.Write(i)).Start();
     }

}

Requests: Do different codes running on different threads have separate stacks? If so, should the variables retain their values, since int is a value type?

0
source share
2 answers

Each thread gets its own stack. The problem you are facing has nothing to do with the stack. The problem is how it generates code for an anonymous delegate. Use a tool, such as a reflector, to understand the code that it generates. The following issues will be fixed:

static void Main() 
        {
            for (int i = 0; i < 10; i++)
            {
                int capture = i;
                new Thread(() => Console.Write(capture)).Start();
            }
        } 

Under the hood

, ( case i) , , , . , - i. :

class SomeClass
{
    public int i { get; set; }

    public void Write()
    {
        Console.WriteLine(i);
    }
}

:

SomeClass someObj = new SomeClass();
for (int i = 0; i < 10; i++)
{
    someObj.i = i;
    new Thread(someObj.Write).Start();
}

, , , . , :

for (int i = 0; i < 10; i++)
{
    SomeClass someObj = new SomeClass();
    someObj.i = i;
    new Thread(someObj.Write).Start();
}

SomeClass. , , . , .

, .

+3

, . . :

class ThreadTest
{
    static void Main()
    {
         for(int i = 0; i < 10; i++)
         {
              int j = i;
              new Thread(() => Console.Write(j)).Start();
         }
    }
} 

? , . int j = i;, . , .

+2

Source: https://habr.com/ru/post/1681344/


All Articles