在ForEach循环中束缚顺序异步任务:这是一个好方法吗?

问题描述 投票:0回答:2

我正在Windows服务上工作,我有两个相互依赖的相关调用,我想针对每个“对”或“一组”调用异步运行。有多种方法可以执行此操作,而我尝试了几种不同的方式并解决了这一问题,因为与一个单独的等待他们自己的Task.WhenAll()调用的代码块相反,使用一个代码块来处理很方便。在我的测试中,这似乎可以按预期工作,但是我以前从未像这样将两个任务链接在一起,我想知道这是否是一个好方法,是否有更合适的方法来获得相同的结果(单个代码块)。

这里是我所拥有的。这看起来像是链接任务的合理方法吗?如果没有,请告诉我原因。

谢谢。 -弗兰克

//get all pending batches
foreach (string batchId in workload)
{
    try
    {
        // I am using this ContinueWith pattern here to aggregate the Tasks
        // which makes it more convenient to handle exceptions in one place
        Task t = bll.GetIncomingBatchAsync(batchId).ContinueWith(
            task => bll.SaveIncomingBatchAsync(task.Result),
            TaskContinuationOptions.OnlyOnRanToCompletion);

        saveBatchTasks.Add(t);
    }
    catch (Exception ex)
    {
        _logger.WriteError(ex, "ProcessWorkloadAsync error building saveBatchTasks!");
        throw ex;
    }
}

try
{
    await Task.WhenAll(saveBatchTasks);
}
catch (Exception ex)
{
    _logger.WriteError(ex, "ProcessWorkloadAsync error executing saveBatchTasks!");
    throw ex;
}
c# asynchronous async-await task-parallel-library continuewith
2个回答
1
投票

否,you should not use ContinueWith。请改用ContinueWith

[如果您担心要在两个函数之间分离逻辑,只需使用本地函数:

await

0
投票

通常不建议将老式的//get all pending batches foreach (string batchId in workload) { try { async Task GetAndSave() { var result = await bll.GetIncomingBatchAsync(batchId); await bll.SaveIncomingBatchAsync(result); } saveBatchTasks.Add(GetAndSave()); } catch (Exception ex) { _logger.WriteError(ex, "ProcessWorkloadAsync error building saveBatchTasks!"); throw ex; } } 方法与async / await结合使用,因为发明了后者以代替前者。如果需要,可以使用ContinueWith在一行中创建任务:

ContinueWith
© www.soinside.com 2019 - 2024. All rights reserved.