What is the best way to use parallelization such as with Parallel.ForEach so that I can rapidly iterate a collection and add items to a new List without violating thread safety but using the performance gain of multiple server cores and plenty of RAM?
public List<Leg> FetchLegs(Trip trip)
{
var result = new List<Leg>();
try
{
// get days
var days = FetchDays(trip);
// add each day's legs to result
Parallel.ForEach<Day>(days, day =>
{
var legs = FetchLegs(day);
result.AddRange(legs);
});
// sort legs by scheduledOut
result.Sort((x, y) => x.scheduledOut.Value.CompareTo(y.scheduledOut.Value));
}
catch (Exception ex)
{
SiAuto.Main.LogException(ex);
System.Diagnostics.Debugger.Break();
}
return result;
}