在我没有使用的测试中Parallel.ForEach()
,处理了 3500 条记录。
但是使用 Parellel,每次尝试都会处理随机数量较少的记录。(3402、3375、3471 等)。我发现 DBSet 不支持并行编程,所以我将我的项目移动到一个列表中,然后再处理该列表。(不理想)一些丢失的记录作为空对象添加到列表中。
我错过了什么?
public int Execute(CalculateAutoClassRatesCommandRequest request)
{
int recordCount = 0;
var autoClassCalculations = new List<AutoClassCalculation>();
var options = new ParallelOptions { MaxDegreeOfParallelism = 2 };
Parallel.ForEach(request.BaseCalculations, options, baseCalculation =>
{
foreach (var autoClass in request.AutoClasses
.Where(autoClass => baseCalculation.BaseClassId == autoClass.BaseClassId)
.Where(autoClass => autoClass.AutoClassForms != null))
{
foreach (var form in autoClass.AutoClassForms)
{
recordCount++;
var calcRate = CreateAutoClassCalculation(autoClass.AutoClassRoundingRules, form, baseCalculation);
autoClassCalculations.Add(calcRate);
}
}
});
foreach (var autoClassCalculation in autoClassCalculations)
{
request.AutoClassCalculationsDbSet.Add(autoClassCalculation);
}
request.ratingContext.SaveChangesWithChangeTracking(request.Identity);
return recordCount;
}
private static AutoClassCalculation CreateAutoClassCalculation(
IEnumerable<AutoClassRoundingRule> autoClassRoundingRules,
AutoClassForm autoClassForm,
BaseCalculation baseCalculation)
{
var autoClassCalculation = new AutoClassCalculation()
{
BaseCalculation = baseCalculation,
AutoClassForm = autoClassForm,
BaseCalculationId = baseCalculation.BaseCalculationId,
AutoClassFormId = autoClassForm.AutoClassFormId
};
var roundingRule = autoClassRoundingRules != null ? autoClassRoundingRules.FindMatchingAutoClassRoundingRule(autoClassForm.AutoClassId, autoClassCalculation.CalcRate) : new AutoClassRoundingRule();
autoClassCalculation.CalculateRate(roundingRule);
return autoClassCalculation;
}