【发布时间】:2021-03-21 14:52:31
【问题描述】:
在我的场景中,我需要处理一个项目列表(伪代码很糟糕),其数量可能是数百或数千。那么,什么是处理这个问题的有效方法呢?这种场景有一些模式/最佳实践吗?
一些具体问题是:
- 我想我应该首先将 QueryResultAsync 上的同步调用更改为异步,但 Micrsoft 文档不建议在紧密循环中使用 async/await。那么,有什么办法吗?
- 是否应该考虑使用同时运行的多个任务来减少延迟?例如,假设有 100 个项目要处理,我创建了同时运行的 10 个任务(每个项目一个)和其中的 WaitAll(),然后将有 10 轮来完成 100 个项目。这样更好吗?
- 我是否应该考虑生产者/消费者模式,其中 3 个生产者用于 Web 请求,1 个消费者负责处理结果?
如果需要您的(场景)信息,请告诉我。
public List<string> Process(List<string> items)
{
List<string> resultItems = new List<string>(items.Count);
foreach (string item in items)
{
string result = QueryResultAsync(item).GetAwaiter().GetResult(); // need to send http request for each item with different urls
resultItems.Add(ProcessResult(result);
}
return resultItems;
}
private static string ProcessResult(string item){
// some plain processing logic without I/O
return result; // a string value
}
【问题讨论】:
-
“Micrsoft doc 不建议在紧密循环中使用 async/await”- 这个文档在哪里?
-
@PauloMorgado,请参阅:docs.microsoft.com/en-us/dotnet/csharp/async,并搜索“在可能的情况下考虑使用 ValueTask”部分。
-
@zjg.robin,这并不是说“不建议在紧密循环中使用 async/await”。这是对性能关键的紧密循环分配的一般评论。并且建议不要使用异步,而是使用
ValueTask而不是Task。
标签: c# concurrency async-await task