0

对线程比较陌生。我有这样的情况:

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 表达式来解决这个问题,但我仍然很想知道为什么它会像它那样工作(或者更确切地说,不能按预期工作)?

谢谢!

史蒂夫

4

0 回答 0