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. , , . , .
, .