2
Next, I have a class that has a string list and the following structure
public class Teste
{
private List<string> _codigos;
public void InsertDB(string[] files)
{
_codigos = new List<string>();
Parallel.ForEach(files, file => Processa(file));
Console.WriteLine(_codigos.Count);
}
private static void Processa(string file)
{
//Efetua um tratamento
string resultado = "Obtem um resultado";
_codigos.Add(resultado);
}
}
The problem is this: if my array files has 7000 elements, my code list, should have 7000 elements. But this does not happen, every time I run the program, the list gets 6989, 6957, 6899, etc.... Always a random number.
The interesting thing is, when I replace Parallel.Foreach() by a simple foreach() as follows:
foreach(string file in files) {
Processa(file);
}
Oh yes I get the expected result, _code with 7000 elements.
What am I doing wrong?
The real code is not this, right? It has a Try-catch?
– Jéf Bueno
the real code is not this, it is only to exemplify the problem. this code already demonstrates the same result that I get.
– Bruno Henri
Another thing: why use the
Parallel.ForEach
?– Jéf Bueno
because the array files usually have 2,000,000 elements. and becomes much faster parallel processing, using all processor cores.
– Bruno Henri
But you can’t just add items to a list in parallel. There is a whole process to add an item to a list, obviously doing this in parallel will cause problems.
– Jéf Bueno