有没有一种方法来处理需求每个结果?
就像注册一个代表/回调当任务完成
是会得到执行,你只需要调整你的思考了一下。
忘记注册回调(ContinueWith
is a dangerous, extremely low-level API)。另外,你几乎从不需要完成任务。相反,根据操作(任务)考虑您的问题。
现在,您拥有一组返回TimeSpan
的任务。该集合中的每个项目都是一个返回TimeSpan
的单个操作。你真正想要做的是引入一个高级操作的概念,它等待原始操作完成,然后执行你的操作后逻辑。
这正是async
/await
是:
private static async Task<TimeSpan> HandleResultAsync(Task<TimeSpan> operation)
{
var result = await operation;
// A task has finished. This will get executed.
// result is of type TimeSpan
...
return result; // (assuming you want to propagate the result)
}
现在,你想这种更高级别的操作应用到您的现有业务。 LINQ的Select
非常适合这样的:
IEnumerable<Task<TimeSpan>> tasks = ...
IEnumerable<Task<TimeSpan>> higherLevelTasks = tasks.Select(HandleResultAsync);
TimeSpan[] results = await Task.WhenAll(higherLevelTasks);
// By the time you get here, all results have been handled individually.
如果您不需要结果的最终集合,这可以进一步简化:
private static async Task HandleResultAsync(Task<TimeSpan> operation)
{
var result = await operation;
// A task has finished. This will get executed.
// result is of type TimeSpan
...
}
IEnumerable<Task<TimeSpan>> tasks = ...
IEnumerable<Task> higherLevelTasks = tasks.Select(HandleResultAsync);
await Task.WhenAll(higherLevelTasks);
也许'任务[I] .ContinueWith()'? –