title: The foreach identifier and closures
body: <p>In the two following snippets, is the first one safe or must you do the second one?</p>
  
  <p>By safe I mean is each thread guaranteed to call the method on the Foo from the same loop iteration in which the thread was created?</p>
  
  <p>Or must you copy the reference to a new variable "local" to each iteration of the loop?</p>
  
  <pre><code>var threads = new List&lt;Thread&gt;();
  foreach (Foo f in ListOfFoo)
  {      
      Thread thread = new Thread(() =&gt; f.DoSomething());
      threads.Add(thread);
      thread.Start();
  }
  </code></pre>
  
  <p>-</p>
  
  <pre><code>var threads = new List&lt;Thread&gt;();
  foreach (Foo f in ListOfFoo)
  {      
      Foo f2 = f;
      Thread thread = new Thread(() =&gt; f2.DoSomething());
      threads.Add(thread);
      thread.Start();
  }
  </code></pre>
  
  <p><strong>Update:</strong> As pointed out in Jon Skeet's answer, this doesn't have anything specifically to do with threading.</p>