I have a simple application with the following code:
FileInfo[] files = (new DirectoryInfo(initialDirectory)).GetFiles(); List<Thread> threads = new List<Thread>(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();
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.
Why is this? Why is the current file ‘f’ variable not getting setup in the anonymous method correctly?
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)
fhas been assigned to point to the last value in the collection, so all 3 threads print that last value.