I am learning to use the Task Parallel Library(TPL) in C#, and wrote the following code (you can copy-past it and run it).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace parallelTaskLibrary
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 6; i++)
{
var t01 = Task.Factory.StartNew(() => Console.WriteLine("in loop: i = {0}", i));
}
Console.WriteLine("press any key to terminate...");
Console.ReadKey();
}
}
}
in the for
loop, the counter index i
cannot start an iteration with a value of i = 6
. However, the output i got is this:
press any key to terminate...
in loop: i = 6
in loop: i = 6
in loop: i = 6
in loop: i = 6
in loop: i = 6
in loop: i = 6
However, in another launch(didn't change in the code), i got this:
in loop: i = 1
in loop: i = 1
in loop: i = 2
in loop: i = 3
in loop: i = 4
in loop: i = 5
press any key to terminate...
which is plausible...
I Debugged the code, and found that i
value is: 0,1,3,4,5,6
How did that happen?
Why i got (i = 6) in the loop?
is there anything wrong in my code?
Note: I'm using visual studio 2010