I am learning about multithreading in C#. It is making me hard, so I am doing some simple programs to understand it better.
I realized that if I have:
static void Main()
{
Task[] tasks = new Task[4];
for (int i = 0; i < 4; i++)
{
tasks[i] = Task.Factory.StartNew(() => {
Console.WriteLine(i);
});
}
Console.ReadKey();
}
The output is 4444, no 0123 like I expected. Why is it?
EDIT:
Sadiq said in his answer that the reason of this behaviour is because i'm closing over a loop variable. But if I add to my code Thread.sleep(500);
outside the lambda statement and inside the loop, I get 0123.
So, why this behaviour supposedly caused by clousures don't occurs with adding this line of code?
it seems to me that the reason of the asked behaviour is other. The code for if you don't understand what I've just written:
static void Main()
{
Task[] tasks = new Task[4];
for (int i = 0; i < 4; i++)
{
tasks[i] = Task.Factory.StartNew(() => {
Console.WriteLine(i);
});
Thread.Sleep(500);
}
//Now the output is: 0123
Console.ReadKey();
}