C# 2.0 Threading Question (anonymous methods) C# 2.0 Threading Question (anonymous methods) multithreading multithreading

C# 2.0 Threading Question (anonymous methods)


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.


Here are some nice articles about anonymous methods in C# and the code that will be generated by compiler:

http://blogs.msdn.com/oldnewthing/archive/2006/08/02/686456.aspx
http://blogs.msdn.com/oldnewthing/archive/2006/08/03/687529.aspx
http://blogs.msdn.com/oldnewthing/archive/2006/08/04/688527.aspx

I think if you did:

   foreach (FileInfo f in files)   {       FileInfo f2 = f; //variable declared inside the loop       Thread t = new Thread(delegate()       {            Console.WriteLine(f2.FullName);       });       threads.Add(t);   }

it would would work the way you wanted it to.


It's because f.FullName is a reference to a variable, and not a value (which is how you tried to use it). By the time you actually start the threads f.FullName was incremented all the way to the end of the array.

Anyway, why iterate through things here twice?

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

However, this is still wrong, and perhaps even worse since you now have a race condition to see which thread goes faster: writing the console item or iterating to the next FileInfo.