0

I am beginner to using Tasks in C#. I am trying to create loop counter and pass it to function, that logs result.

The loop looks like this:

List<Task> levelGroupsTasks = new List<Task>();
foreach (TableWithLevel table in levelGroup.Value)
{
    counter++;
    
    // Section for adding task into list
}

await Task.WhenAll(levelGroupsTasks);

I tried this aproach:

levelGroupsTasks.Add(Task.Run(() => DeleteTableFromDestination(table.TableName, count, counter)));

But the logged counter for each table was same value, for example starting at 238 index (1-269 expected)

I tried add counter++ directly in Task.Run like this:

levelGroupsTasks.Add(Task.Run(() => DeleteTableFromDestination(table.TableName, count, counter++)));

This logged correct values for each table from 1 - 269.

I tried another aproach like this with new wrap function:

levelGroupsTasks.Add(DeleteTableFromDestinationAsync(table.TableName, count, counter));

private async Task DeleteTableFromDestinationAsync(string tableName, int count, int counter) => await Task.Run(() => DeleteTableFromDestination(tableName, count, counter));

And the result was also correct.

My question is, why the first aproach with passing Task.Run is not working and passing wrong values of counter?

uvr
  • 515
  • 4
  • 12
Michal Fiala
  • 33
  • 1
  • 4
  • I've linked your question to another one which asks the same thing, and has some great answers. The situation is slightly different, but the cause is the same: the variable itself is being captured, and then the variable is incremented before the `Task.Run` accesses it – canton7 May 05 '21 at 09:41
  • @canton7 Thank you for help finding the answer! – Michal Fiala May 06 '21 at 11:14

0 Answers0