2

The following code produces an event log of 14, 15, 16, 16 when I expect 13, 14, 15, 16, i.e. each number to be written to event log once, regardless of order.

The question is why is it missing 13 and duplicating 16?

List<int> webReports = new List<int>{13,14,15,16};

List<Task> tasks = new List<Task>();

foreach (int webReportNo in webReports)
{
    tasks.Add(Task.Factory.StartNew(() => DoStuff(webReportNo)));
}

private static void DoStuff(int webReportNo)
{
    //Write webReportNo to event log.
}
Paul Zahra
  • 9,522
  • 8
  • 54
  • 76
  • This works fine for me, perhaps it's something to do with closures. What version of compiler are you using here? – DavidG Oct 16 '15 at 09:49
  • 3
    Presumably you're using c# 4.0 compiler or lower. Closing over the loop issue is fixed in c# 5.0 – Sriram Sakthivel Oct 16 '15 at 09:53
  • @SriramSakthivel: as far as I understand, in case of 4.0 OP should get 13, 13, 13, 13 in the log. Isn't it? – Dennis Oct 16 '15 at 09:56
  • 1
    @Dennis No. That depends on when `StartNew` is executed. If it executes delayed, he'll get 16, 16, 16... otherwise some unpredictable values depending on thread scheduling and threadpool resources at the time. – Sriram Sakthivel Oct 16 '15 at 09:58
  • 1
    Ah you beauties!... it was the modified closure problem, I was aware of it for linq to entities, but didn't think it was an issue with Tasks... THANKS! – Paul Zahra Oct 16 '15 at 10:02
  • @SriramSakthivel: yep, I've confused with last value. – Dennis Oct 16 '15 at 10:02
  • P.S. You were correct that I am using C# 4.0 released with .NET 4 and VS2010 (Runtime v4.0.30319) – Paul Zahra Oct 16 '15 at 10:32

0 Answers0