The reason why C # evaluates anonymous methods is that they are not true closures. This has nothing to do with TPL. The following code prints all d's. This is not what would be expected during the year.
List<Task> tasks = new List<Task>();
List<string> lists = new List<string>();
lists.AddRange(new string[] { "a", "b", "c", "d" });
foreach (var list in lists)
{
tasks.Add(Task.Factory.StartNew(() =>
{
Console.WriteLine(list);
}));
}
, list , . list . , :
List<Task> tasks = new List<Task>();
List<string> lists = new List<string>();
lists.AddRange(new string[] { "a", "b", "c", "d" });
foreach (var list in lists)
{
var localList = list;
tasks.Add(Task.Factory.StartNew(() =>
{
Console.WriteLine(localList);
}));
}
.
:
http://blogs.msdn.com/b/abhinaba/archive/2005/10/18/482180.aspx