Reputation: 985
Sequential Tasks returns same output even lock the output. Even no clouser variables. For example
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());
And the method is
public void IteratingFunction(int s)
{
lock (Console.Out)
{
Console.WriteLine("Running task is: {0}",s);
}
}
Upvotes: 0
Views: 46
Reputation: 2852
You are accessing the modified closure, try capture the value of x outside of the lambda function:
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());
Upvotes: 2