title: Why task factory in loop prints beyond loop index?
body: <p>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).</p>
  
  <pre><code>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 &lt; 6; i++)
              {
                  var t01 = Task.Factory.StartNew(() =&gt; Console.WriteLine("in loop: i = {0}", i));
              }
  
              Console.WriteLine("press any key to terminate...");
              Console.ReadKey();
          }      
      }
  }
  </code></pre>
  
  <p>in the <code>for</code> loop, the counter index <code>i</code> cannot start an iteration with a value of <code>i = 6</code>. However, the output i got is this:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>However, in another launch(didn't change in the code), i got this:</p>
  
  <pre><code>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...
  </code></pre>
  
  <p>which is plausible...</p>
  
  <p>I Debugged the code, and found that <code>i</code> value is: <code>0,1,3,4,5,6</code> </p>
  
  <p><strong>How did that happen?</strong></p>
  
  <p><strong>Why i got (i = 6) in the loop?</strong></p>
  
  <p><strong>is there anything wrong in my code?</strong></p>
  
  <p><em>Note:</em> I'm using visual studio 2010</p>