6
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 whenever the Associate method is executed. I put a Thread.Sleep(10);
only to check whether it would be a competition problem and the problem was "solved". What is the correct way to use a list thread safe
to modify each item of a collection distributed in several Tasks?
Debugging the code a little more, I noticed that the difference in values is actually on the line dado.Colecao = await consultanobanco();
Within the method consultanobanco();
the return is correct. However, when arriving at the assignment to dado.Colecao
it comes wrong. Modifying of await consultanobanco();
for consultanobanco().Result
the result is returned as expected.
Any reason for this behavior? What is the difference between await and . Result in this scenario?
already tried to await Addirasync?
– Thiago Custodio