顺序任务返回相同的输出,甚至锁定输出。甚至没有clouser变量。 例如
List<Task> tasks = new List<Task>();
for (int i = 0; i < 10; i++)
{
Task t = Task.Factory.StartNew((arg) =>
{
int taskid = (int)i;
IteratingFunction(taskid);
}, i);
tasks.Add(t);
}
Task.WaitAll(tasks.ToArray());
方法是
public void IteratingFunction(int s)
{
lock (Console.Out)
{
Console.WriteLine("Running task is: {0}",s);
}
}
答案 0 :(得分:2)
您正在访问修改后的闭包,尝试捕获lambda函数之外的x值:
List<Task> tasks = new List<Task>();
for (int i = 0; i < 10; i++)
{
// capture taskid here
int taskid = (int)i;
Task t = Task.Factory.StartNew((arg) =>
{
IteratingFunction(taskid);
}, i);
tasks.Add(t);
}
Task.WaitAll(tasks.ToArray());