<p>I have a simple application with the following code:</p>

<pre><code>   FileInfo[] files = (new DirectoryInfo(initialDirectory)).GetFiles();
   List&lt;Thread&gt; threads = new List&lt;Thread&gt;(files.Length);

   foreach (FileInfo f in files)
   {
       Thread t = new Thread(delegate()
       {
            Console.WriteLine(f.FullName);
       });
       threads.Add(t);
   }

   foreach (Thread t in threads)
       t.Start();
</code></pre>

<p>Lets say in 'I=initialDirectory' directory I have 3 files.  This application should then create 3 threads, with each thread printing off one of the file names; however, instead each thread will print off the name of the last file in the 'files' array.</p>

<p>Why is this?  Why is the current file 'f' variable not getting setup in the anonymous method correctly?</p>

The anonymous method keeps a
reference
to the variable in the enclosing block -- not the actual value of the variable.
By the time the methods are actually executed (when you start the threads)
```
f
```
has been assigned to point to the last value in the collection, so all 3 threads print that last value.