title: Captured variables in a thread in a loop in C#, what is the solution?
body: <p>I came across this example that demonstrates the case of <code>Captured Variables</code> within a <code>Thread</code> and a loop :</p>
  
  <p><strong>Code 1</strong></p>
  
  <pre><code>for (int i = 0; i &lt; 10; i++)
  {
     new Thread(() =&gt; Console.Write(i)).Start();
  }
  </code></pre>
  
  <p><strong>Result 1</strong></p>
  
  <p><code>0223558779</code></p>
  
  <p>The suggested solution is said to be creating a temporary variable as follows :</p>
  
  <p><strong>Code 2</strong></p>
  
  <pre><code>for (int j = 0; j &lt; 10; j++)
  {
      int temp = j;
      new Thread(() =&gt; Console.Write(temp)).Start();
  }
  </code></pre>
  
  <p><strong>Result 2</strong></p>
  
  <p><code>0124356879</code></p>
  
  <p>It seems that this solution only eliminates redundancy by using the <code>temp</code> variable which will create 10 different memory locations, yet the sequence is still not ordered, well I understand the reason, which is related to the threads not being too fast executing <code>Console.Write(temp)</code> before iterating and starting the future threads,  I tried to slow down the loop by sleeping the main thread giving time to each thread to write properly by doing :</p>
  
  <p><strong>Code 3</strong></p>
  
  <pre><code>for (int i = 0; i &lt; 10; i++)
  {
     new Thread(() =&gt; Console.Write(i)).Start();
     Thread.Sleep(10);   
  }
  </code></pre>
  
  <p>It resolves the problem, but I don't consider this a real solution when it comes to real scenarios, is there a trick or a practice I'm missing here to show a complete correct sequence like <code>0123456789</code> ?</p>