我正在迈出并行编程的第一步。我将CalculateSlots 重写为CalculateSlotsAsync。它看起来可以正常工作(快 3 倍)。
我的问题是:写对了吗?我是否需要使用最新的异步离开模式,如果是,如何?
private void CalculateSlots(bool isCalculateAllSlots)
{
foreach (IndicatorSlot indicatorSlot in strategy.Slot)
{
if (isCalculateAllSlots || !indicatorSlot.IsCalculated)
CalculateStrategySlot(indicatorSlot.SlotNumber);
}
}
private void CalculateSlotsAsync(bool isCalculateAllSlots)
{
var tasks = new List<Task>();
foreach (IIndicatorSlot indicatorSlot in strategy.Slot)
{
if (isCalculateAllSlots || !indicatorSlot.IsCalculated)
{
IIndicatorSlot slot = indicatorSlot;
Task task = Task.Factory.StartNew(() => CalculateStrategySlot(slot.SlotNumber));
tasks.Add(task);
}
}
Task.WaitAll(tasks.ToArray());
}
在 i7-3630QM @2.40Gh 上测试
// Executed for 96 sec.
for (int i = 0; i < 1000; i++)
CalculateSlots(true);
// Executed for 34 sec.
for (int i = 0; i < 1000; i++)
CalculateSlotsAsync(true);