【发布时间】:2018-06-25 11:09:52
【问题描述】:
这是在底层方法中发出 3 个 HTTP 请求以获取信息的代码,其中输入的 PIN ID 存在于 3 个产品之一中,这些产品为其提供 REST API。
它创建并等待 3 个任务。我想仔细检查这些任务是并行执行还是顺序执行
public async Task<Product> IdentifyPin(TokenParams token, string pin)
{
Task<ApiResponse<ProductInfo, ErrorData>> productATask = GetProductAInfo(ProductType.A, pin, token.JwtToken, true);
Task<ApiResponse<ProductInfo, ErrorData>> productBTask = GetProductBInfo(ProductType.B, pin, token.JwtToken, true);
Task<ApiResponse<ProductInfo, ErrorData>> productCTask = GetProdctCInfo(pin, token.JwtToken, true);
ApiResponse<ProductInfo, ErrorData> productAInfoResponse = null;
ApiResponse< ProductInfo, ErrorData> productBInfoResponse = null;
ApiResponse< ProductInfo, ErrorData> productCInfoResponse = null;
// await HTTP response from ProductA info endpoint
try
{
productAInfoResponse = await productATask.ConfigureAwait(false);
}
catch (Exception ex)
{
this.Log().Error(ex.Message, exception: ex);
}
// await HTTP response from ProductB info endpoint
try
{
productBInfoResponse = await productBTask.ConfigureAwait(false);
}
catch (Exception ex)
{
this.Log().Error(ex.Message, exception: ex);
}
// await HTTP response from ProductC info endpoint
try
{
productCInfoResponse = await productCTask.ConfigureAwait(false);
}
catch (Exception ex)
{
this.Log().Error(ex.Message, exception: ex);
}
// Mapping responses to new Product() and returning it
// ...
}
【问题讨论】:
-
我相信任务应该并行运行,但会在等待时按顺序阻塞。
-
实际运行代码时发生了什么?它们是并行运行还是按顺序运行?
-
您可能需要考虑 Task.WhenAll()
标签: c# .net async-await task-parallel-library