Search code examples
c#continuewith

Is reassigning a task value necessary when not using task.ContinueWith()


When reading a post, Starting Tasks In foreach Loop Uses Value of Last Item), the marked answer makes a lot of sense. The author created a new variable, pathCopy, to use in the task. My question is, is this only necessary when Task.ContinueWith() is used?

Here is an example:

    private void GetAuditFiles()
    {
        _auditFiles = new ConcurrentBag<AuditFile>();

        var tasks = new List<Task>();
        foreach (var auditFile in Directory.GetFiles(_properties.AuditFileOutputPath))
        {
            var taskfile = auditFile;

            tasks.Add(Task.Factory.StartNew(() =>
            {
                var file = DeserializeProcessProperties<AuditFile>(File.ReadAllText(taskfile));
                file.filename = Path.GetFileName(taskfile);
                _auditFiles.Add(file);
            }));
        }

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

Do I need to set a variable like this "var taskfile = auditFile;"?

Note: I am using an updated version of VS 2017 and its C# compiler.


Solution

  • Ok, thanks to damien-the-unbeliever, for pointing me back to Eric Lippert's Blog: closing over the loop variable part two.

    So the short answer is yes, if I am c# v 4.0 or earlier. It is unneeded in any case if at c# 5.0 or later.