0

Rather new to threading. I have a situation like this:

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;
    }
}

Which invariably, when run, gives me this:

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

In other words, the thread parameter is not what I would expect.

I'm guessing I could get around this by using a ParameterizedThreadStart delegate instead of an anonymous lambda expression, but I'm still curious to know why this works as it does (or rahter, doesn't work as expected)?

Thanks!

Steve

Steve Gore
  • 356
  • 6
  • 12
  • 3
    See http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx – Gabe Sep 07 '13 at 02:53
  • What is "expected" behavior? Threads are asynchronous, so they don't depend/look at one another. What's confusing? – BLaZuRE Sep 07 '13 at 02:54
  • 1
    @BLaZuRE, he's expecting Dispatching: 0->4 and In thread: 0->4. However, the closure is over the variable article, not the value contained therein (in C# 4, this will change in C# 5), as explained in Gabe's linked article. Basically, the variable is changing underneath the thread body, so it's printing the "wrong" article. – Tawnos Sep 07 '13 at 02:56
  • Thanks the suggested duplicate definite applies! – Steve Gore Sep 07 '13 at 02:58

0 Answers0