我遇到了C#线程奇怪的问题。奇怪的线程与C#
这是我使用线程“激活”agentList中每个代理的Print()函数的示例程序。
class Program {
static void Main(string[] args) {
List<Agent> agentList = new List<Agent>();
agentList.Add(new Agent("lion"));
agentList.Add(new Agent("cat"));
agentList.Add(new Agent("dog"));
agentList.Add(new Agent("bird"));
foreach (var agent in agentList) {
new Thread(() => agent.Print()).Start();
}
Console.ReadLine();
}
}
class Agent {
public string Name { get; set; }
public Agent(string name) {
this.Name = name;
}
public void Print() {
Console.WriteLine("Agent {0} is called", this.Name);
}
}
这里是结果,当我运行上面的程序:
Agent cat is called
Agent dog is called
Agent bird is called
Agent bird is called
但我期望的东西包含了所有4剂,如
Agent lion is called
Agent cat is called
Agent dog is called
Agent bird is called
最令人惊奇的是,如果我在foreach外面调用线程,它就可以工作!
class Program {
static void Main(string[] args) {
List<Agent> agentList = new List<Agent>();
agentList.Add(new Agent("leecom"));
agentList.Add(new Agent("huanlv"));
agentList.Add(new Agent("peter"));
agentList.Add(new Agent("steve"));
new Thread(() => agentList[0].Print()).Start();
new Thread(() => agentList[1].Print()).Start();
new Thread(() => agentList[2].Print()).Start();
new Thread(() => agentList[3].Print()).Start();
Console.ReadLine();
}
}
上述代码的结果正是我所期望的。那么这里有什么问题?
这就是当你关闭了循环变量会发生什么:http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing -over-the-loop-variable-considered-harmful.aspx – dlev
@dlev,你应该发布一个答案,以便他可以标记它已解决。你的回答是正确的。 –
你知道,如果你使用的是.Net 4.0,你可以在每个循环中使用Parallel来完成你想要的任务。我认为这样会更合适。 – jlafay