在下面的两个片段中,第一个是安全的,还是必须执行第二个?安全地说,我的意思是每个线程是否保证从创建线程的同一个循环迭代中调用foo上的方法?或者必须将对新变量“local”的引用复制到循环的每一次迭代中?var threads = new List<Thread>();foreach (Foo f in ListOfFoo){
Thread thread = new Thread(() => f.DoSomething());
threads.Add(thread);
thread.Start();}-var threads = new List<Thread>();foreach (Foo f in ListOfFoo){
Foo f2 = f;
Thread thread = new Thread(() => f2.DoSomething());
threads.Add(thread);
thread.Start();}最新情况:正如JonSkeet的答案所指出的,这与线程无关。foreach标识符和闭包
3 回答
慕桂英3389331
TA贡献2036条经验 获得超8个赞
在C#5之前
foreach
Foo f;while(iterator.MoveNext()){
f = iterator.Current;
// do something with f}f
foreach(Foo f in ...) {
Foo tmp = f;
// do something with tmp}tmp
static void Main()
{
int[] data = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
foreach (int i in data)
{
new Thread(() => Console.WriteLine(i)).Start();
}
Console.ReadLine();
}1 3 4 4 5 7 7 8 9 9
foreach (int i in data)
{
int j = i;
new Thread(() => Console.WriteLine(j)).Start();
}
胡说叔叔
TA贡献1804条经验 获得超8个赞
using System;using System.Collections.Generic;class Test{
static void Main()
{
List<Action> badActions = new List<Action>();
List<Action> goodActions = new List<Action>();
for (int i=0; i < 10; i++)
{
int copy = i;
badActions.Add(() => Console.WriteLine(i));
goodActions.Add(() => Console.WriteLine(copy));
}
Console.WriteLine("Bad actions:");
foreach (Action action in badActions)
{
action();
}
Console.WriteLine("Good actions:");
foreach (Action action in goodActions)
{
action();
}
}}- 3 回答
- 0 关注
- 886 浏览
添加回答
举报
0/150
提交
取消
