Странные потоки с C #

Я столкнулся со странной проблемой с потоками C #.

Это мой пример программы, использующей поток для «активации» функции 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();
    }
}

Результат приведенного выше кода - именно то, что я ожидал. Так в чем проблема?

5
задан Hieu Nguyen 9 November 2011 в 15:31
поделиться