Here it goes a tricky one (maybe not for experts). I'm learning about concurrency in C# and I'm playing around with some dummy code to test the fundamentals of threads. Im surprised about how is possible that the following code prints the value 10 sometimes.
Thread[] pool = new Thread[10];
for(int i = 0; i < 10; i++)
{
pool[i] = new Thread(() => Console.Write(i));
pool[i].Start();
}
Typical output is like 76881079777
. I know is the value 10 and not 1 and 0 because the for loop body executes 10 times (not strictly sure, but I couldn't break C#). I'm even more surprised why this does not throw an IndexOutOfRange
exception in the statement pool[i] = new Thread(() => Console.Write(i));
As long as I know, the for loop executes like following:
- Check the condition (
i < 10
) - Executes the body if condition is true
- Increments the control variable (
i++
) - Repeat
So, assuming that, is imposible for me to understand how the body can be executed with the value 10. Any ideas?