Generating new tasks in a foreach loop
        Posted  
        
            by Scott Chamberlain
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Scott Chamberlain
        
        
        
        Published on 2010-05-27T21:59:30Z
        Indexed on 
            2010/05/27
            22:01 UTC
        
        
        Read the original article
        Hit count: 215
        
I know from the codeing guidlines that I have read you should not do
for (int i = 0; i < 5; i++) 
{ 
    Task.Factory.StartNew(() => Console.WriteLine(i));
}
Console.ReadLine();
as it will write 5 5's, I understand that and I think i understand why it is happening. I know the solution is just to do
for (int i = 0; i < 5; i++) 
{ 
    int localI = i;
    Task.Factory.StartNew(() => Console.WriteLine(localI));
}
Console.ReadLine();
However is something like this ok to do?
Task currentTask = myFirstTask;
currentTask.Start();
foreach (Task task in _TaskList)
{
    currentTask.ContinueWith((antecendent) =>
    {
        if(antecendent.IsCompleated)
        {
             task.Start();
        }
        else
            //do error handling;
    });
    currentTask = task;
}
}
or do i need to do this?
Task currentTask = myFirstTask;
foreach (Task task in _TaskList)
{
    Task localTask = task;
    currentTask.ContinueWith((antecendent) =>
    {
        if(antecendent.IsCompleated)
        {
             localTask.Start();
        }
        else
            //do error handling;
    });
    currentTask = task;
}
© Stack Overflow or respective owner