I have the following pseudo-code:
public void Associar(List<Data> dados)
{
List<Task> tasks = new List<Task>();
foreach(dado in dados)
{
tasks.Add(AdicionarAsync(dado));
}
Task.WaitAll(tasks.ToArray());
Debug.WriteLine(dados.Select(e => e.Colecao).Sum(e => e.Count));
}
public async Task AdicionarAsync(Data dado)
{
dado.Colecao = await consultanobanco(dado.Id);
}
The output of this code should always be 411 (equivalent to the sum of the records in the database). However, the result varies each time the Join method is run. I put Thread.Sleep(10);
just to check if it was a competition problem and the problem was solved. What is the correct way to use a thread safe
list to modify each item in a collection distributed across multiple Tasks?
Debugging the code a bit more, I noticed that the difference of values is actually in the line dado.Colecao = await consultanobanco();
Within method consultanobanco();
return is correct. However, when it reaches the assignment to dado.Colecao
it goes wrong. Modifying from await consultanobanco();
to consultanobanco().Result
the result is returned as expected.
Any reason for this behavior? What is the difference between await and .Result in this scenario?