您可以使用一种在它们完成时重新排序它们的方法。这是Jon Skeet和Stephen Toub描述的一个很好的技巧,我的AsyncEx 库也支持这个技巧。
所有三个实现都非常相似。采取我自己的实现:
/// <summary>
/// Creates a new array of tasks which complete in order.
/// </summary>
/// <typeparam name="T">The type of the results of the tasks.</typeparam>
/// <param name="tasks">The tasks to order by completion.</param>
public static Task<T>[] OrderByCompletion<T>(this IEnumerable<Task<T>> tasks)
{
// This is a combination of Jon Skeet's approach and Stephen Toub's approach:
// http://msmvps.com/blogs/jon_skeet/archive/2012/01/16/eduasync-part-19-ordering-by-completion-ahead-of-time.aspx
// http://blogs.msdn.com/b/pfxteam/archive/2012/08/02/processing-tasks-as-they-complete.aspx
// Reify the source task sequence.
var taskArray = tasks.ToArray();
// Allocate a TCS array and an array of the resulting tasks.
var numTasks = taskArray.Length;
var tcs = new TaskCompletionSource<T>[numTasks];
var ret = new Task<T>[numTasks];
// As each task completes, complete the next tcs.
int lastIndex = -1;
Action<Task<T>> continuation = task =>
{
var index = Interlocked.Increment(ref lastIndex);
tcs[index].TryCompleteFromCompletedTask(task);
};
// Fill out the arrays and attach the continuations.
for (int i = 0; i != numTasks; ++i)
{
tcs[i] = new TaskCompletionSource<T>();
ret[i] = tcs[i].Task;
taskArray[i].ContinueWith(continuation, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
return ret;
}
然后,您可以这样使用它:
var tasks = new[]
{
client.GetAsync("http://example.com/"),
client.GetAsync("http://stackoverflow.com/"),
};
var orderedTasks = tasks.OrderByCompletion();
foreach (var task in orderedTasks)
{
var response = await task;
HandleResponse(response);
}
另一种方法是使用TPL Dataflow;随着每个任务的完成,将其操作发布到一个ActionBlock<T>
,如下所示:
var block = new ActionBlock<string>(HandleResponse);
var tasks = new[]
{
client.GetAsync("http://example.com/"),
client.GetAsync("http://stackoverflow.com/"),
};
foreach (var task in tasks)
{
task.ContinueWith(t =>
{
if (t.IsFaulted)
((IDataflowBlock)block).Fault(t.Exception.InnerException);
else
block.Post(t.Result);
});
}
以上任何一个答案都可以正常工作。如果您的其余代码使用/可以使用 TPL 数据流,那么您可能更喜欢该解决方案。