'foreach' failing when using Parallel Task Library

Posted by Chris Arnold on Stack Overflow See other posts from Stack Overflow or by Chris Arnold
Published on 2010-06-02T09:17:14Z Indexed on 2010/06/02 10:43 UTC
Read the original article Hit count: 368

The following code creates the correct number of files, but every file contains the contents of the first list. Can anyone spot what I've done wrong please?

private IList<List<string>> GetLists()
{
  // Code omitted for brevity...
}

private void DoSomethingInParallel()
{
  var lists = GetLists();

  var tasks = new List<Task>();

  var factory = new TaskFactory();

  foreach (var list in lists)
  {
    tasks.Add(factory.StartNew(() =>
    {
      WriteListToLogFile(list);
    }));
  }

  Task.WaitAll(tasks.ToArray());
}

© Stack Overflow or respective owner

Related posts about .net-4.0

Related posts about parallel