gpt4 book ai didi

c# - 使用异步方法选择

转载 作者:太空宇宙 更新时间:2023-11-03 22:29:00 24 4
gpt4 key购买 nike

我找到了 question这对我来说真的很有用,但我仍然无法意识到 LINQ 世界中的等价物有进一步的构造:

public async Task<List<ObjectInfo>> GetObjectsInfo(string[] objectIds)
{
var result = new List<ObjectInfo>(objectIds.Length);
foreach (var id in objectIds)
{
result.Add(await GetObjectInfo(id));
}

return result;
}

如果我改写

var result = await Task.WhenAll(objectIds.Select(id => GetObjectInfo(id)));

这些任务不会同时启动吗?就我而言,串联运行它们会更好。

编辑 1:回答 Theodor Zoulias 的评论。

当然,我忘记了方法名称中的 Async 后缀!

方法 GetObjectInfoAsync 向外部服务发出 http 请求。此外,此服务对请求频率有限制,因此我使用以下构造。

            using (var throttler = new Throttler(clientId))
{
while (!throttler.IsCallAllowed(out var waitTime))
{
await Task.Delay(waitTime);
}

var response = await client.PerformHttpRequestAsync(request);
return response.Content.FromJson<TResponse>(serializerSettings);
}

Throttler 知道每个客户端的最后请求时间。

最佳答案

在使用whenAll

时,您应该考虑以下注意事项

Quotes taken from MS documentation

If any of the supplied tasks completes in a faulted state, the returned task will also complete in a Faulted state, where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied tasks.

If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the Canceled state.

If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the RanToCompletion state.

If the supplied array/enumerable contains no tasks, the returned task will immediately transition to a RanToCompletion state before it's returned to the caller.

这意味着虽然项目将可能同时运行(您无法知道它是如何运行的,因为它取决于机器的资源并且您无法知道顺序),上面不能'无法避免。

如果您想对每种情况和特定顺序进行特定的错误处理,那么第一个解决方案就是可行的方法。它有点超过了 async/await 的要点,但不是全部。即使按顺序执行异步项,您的线程至少也不会进入休眠状态,并且在可等待对象准备就绪之前仍可使用。

关于c# - 使用异步方法选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59189516/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com