我使用IAsyncEnumerable返回API中的分页结果,如下所示:
public async IAsyncEnumerable<ApiObject> GetResults(){
int startIndex = 0;
PaginatedResponse<ApiObject> response;
do {
response = await _client.GetResults(_endpoint, startIndex, _pageSize);
foreach (var obj in response.Items){
yield return obj;
}
startIndex = response.StartIndex + response.Count;
} while (response.StartIndex + response.Count < response.Total);
}我想要的是并行地发送多个页面的请求,并在每个页面出现时返回给IAsyncEnumerable。秩序并不重要。
我想要做的事有可能吗?可以让多个异步任务写入我的方法返回的同一个IAsyncEnumerable吗?我能想到的最好的方法是让任务写入一个公共IList,然后在所有任务完成后,遍历该IList并返回所有元素:
public async Task<IAsyncEnumerable<ApiObject>> GetResults(){
int totalPages = _client.MagicGetTotalPagesMethod();
IList<ApiObject> results = new List<ApiObject>();
var tasks = Enumerable.Range(0,totalPages).Select(async x => {
// my goal is to somehow return from here, rather than aggregating into the IList and returning after all tasks are done
results.AddRange(await _client.GetResults(_endpoint, x*_pageSize, _pageSize));
});
await Task.WhenAll(tasks);
foreach (var result in results){
yield return result;
}
}这部分地解决了这个问题,一次发出多个请求,但我们仍然需要等待所有请求都返回,然后GetResults的使用者才能使用结果。
发布于 2021-11-18 17:11:40
您可以使用the ability to order a sequence of tasks by completion使这种方法非常简单。
var tasks = Enumerable.Range(0,totalPages).Select(x =>
client.GetResults(_endpoint, x*_pageSize, _pageSize));
foreach(var task in tasks.Order())
foreach(var item in await task)
yield return item;https://stackoverflow.com/questions/70023736
复制相似问题