I was meet a strange bug, when I used the following code:
for (int i = 0; i < 10; i++)
{
new Thread(() => Console.Write(i)).Start();
}
Console.WriteLine();
for (int i = 0; i < 10; i++)
{
var temp = i;
new Thread(() => Console.Write(temp)).Start();
}
Results was unpredictable:
444554689
100123456789
I can`t understand why in the second cycle there is a problem with threads if I use a temporary variable. I think this is due to the same name for variable "i" , because when I change it, the problem was dissapeared. But they have different scopes.
So, what is the reason for this behavior?