Joh*_*ohn 12 c# multithreading anonymous-methods .net-2.0
我有一个简单的应用程序与以下代码:
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();
Run Code Online (Sandbox Code Playgroud)
让我们说在'I = initialDirectory'目录中我有3个文件.然后,该应用程序应创建3个线程,每个线程打印一个文件名; 但是,每个线程将打印出'files'数组中最后一个文件的名称.
为什么是这样?为什么当前文件'f'变量无法正确设置匿名方法?
这里有一些关于C#中匿名方法的好文章以及将由编译器生成的代码:
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
我想如果你这样做了:
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);
}
它会以你想要的方式工作.