I’m having a hard time in understanding 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();
}
}
Queries:
Different code running in different thread have seperate stacks? If yes, than variables should preserve their values as int is a value type?
Each thread gets its own stack. The problem that you are facing has nothing to do with stack. The problem is the way it is generating code for your anonymous delegate. Use tool like refelector to understand the code that it is generating. The following will fix your problem:
Under the hood
Whenever you use a variable from outer scope (in your case variable i) in anonymous delegate, the compiler generates a new class that wraps anonymous function along with the data that it uses from the outer scope. So in your case the generated class contains – one function and data member to capture the value of variable i. The class definition looks something like:
The compiler re-writes your code as follows:
and hence the problem – that you are facing. When you capture a variable, the compiler does the following:
Note the difference in SomeClass instantiation. When you capture a variable, it creates as many instances as there are number of iterations. If you do not capture a variable, it tries to use the same instance for all iterations.
Hope, the above explanation will clarify your doubt.
Thanks