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 files array has 7000 elements, my _codigos list should have 7000 elements. But that does not happen, every time I run the program, the list goes with 6989, 6957, 6899, etc ... Always a random number.
The interesting thing is that when I replace Parallel.ForEach () with a simple foreach () as follows:
foreach(string file in files) {
Processa(file);
}
Well yes I get the expected result, _code with 7000 elements.
What am I doing wrong?