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?