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

半世苍凉 提交于 2019-12-11 16:44:30

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/53303874/is-reassigning-a-task-value-necessary-when-not-using-task-continuewith

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!