意外的线程行为

时间:2013-09-07 02:50:21

标签: c# multithreading

线程新手。我有这样的情况:

class Program
{
    static void Main(string[] args)
    {

        List<NewsItem> newsItems = new List<NewsItem>();
        for (int i = 0; i < 5; i++)
        {
            NewsItem item = new NewsItem(i.ToString());
            newsItems.Add(item);
        }

        List<Thread> workerThreads = new List<Thread>();
        foreach (NewsItem article in newsItems)
        {
            Console.WriteLine("Dispatching: " + article.Headline);
            Thread thread = new Thread(() =>
            {
                Console.WriteLine("In thread:" + article.Headline);
            });
            workerThreads.Add(thread);
            thread.Start();
        }

        foreach (Thread thread in workerThreads)
        {
            thread.Join();
        }

        Console.ReadKey();
    }
}

class NewsItem
{
    public string Headline { get; set; }

    public NewsItem(string headline)
    {
        Headline = headline;
    }
}

跑步时总是给我这个:

Dispatching: 0
Dispatching: 1
Dispatching: 2
In thread: 2
Dispatching: 3
In thread: 3
In thread: 2
Dispatching: 4
In thread: 4
In thread: 4

换句话说,线程参数不是我所期望的。

我猜我可以通过使用ParameterizedThreadStart委托而不是匿名的lambda表达来解决这个问题,但我仍然很想知道为什么这样可行(或者rahter,不能按预期工作)?

谢谢!

史蒂夫

0 个答案:

没有答案