Example on how to write parallel code
public List<string> ProcessX(CancellationToken cancToken = default)
{
// sequential code
// ...
// list that we want to be able to process faster
List<Animal> animals = // ...
// multithread safe collection
var animalsDTO = new ConcurrentBag<AnimalDTO>();
var options = new ParallelOptions
{
CancellationToken = cancToken,
MaxDegreeOfParallelism = GetMaxDegreeOfParallelism()
};
Parallel.ForEach(animals, options, animal =>
{
// process single animal
// this is just an example to map animal to animalDTO
// ...
animalsDTO.Add(Map(animal));
});
}
private int GetMaxDegreeOfParallelism()
{
string configured = config["ANIMALS_PARALLELISM"] ?? "4";
int degree;
if(!int.TryParse(configured, out degree))
{
degree = 4;
}
return degree;
}