The foreach identifier and closures

22 浏览
0 Comments

The foreach identifier and closures

在下面的两个片段中,第一个是否安全,还是必须使用第二个?

所谓安全是指每个线程是否保证在创建线程的循环迭代中调用Foo的方法?

或者必须将引用复制到一个新的变量"local"中的每个循环迭代中?

代码:

var threads = new List();

foreach (Foo f in ListOfFoo)

{

Thread thread = new Thread(() => f.DoSomething());

threads.Add(thread);

thread.Start();

}

-

代码:

var threads = new List();

foreach (Foo f in ListOfFoo)

{

Foo f2 = f;

Thread thread = new Thread(() => f2.DoSomething());

threads.Add(thread);

thread.Start();

}

更新:正如Jon Skeet的答案中指出的那样,这与线程无关。

0