我将使用asp.net web api 2和Entity Framework 6。
原伪代码
public IHttpActionResult GetProductLabel(int productId)
{
var productDetails = repository.GetProductDetails(productId);
var label = labelCalculator.Render(productDetails);
return Ok(label);
}
修改后的代码
public async Task<IHttpActionResult> GetProductLabel(int productId)
{
var productDetails = await repository.GetProductDetailsAsync(productId); // 1 long second as this call goes into sub services
var label = labelCalculator.Render(productDetails); // 1.5 seconds synchrounous code
return Ok(label);
}
在我的更改之前,一切都同步运行。
在我的更改之后,对远程服务的调用采用了async-await方式,该服务再次调用数据库。
然后我对一个只提供同步方法的渲染库进行同步调用。计算需要1.5秒钟。
即使第二个调用没有使用async-await方式,我对远程database_service的调用仍有好处吗?还有什么可以改进的地方吗?
注意
我问这个问题的原因是:
"使用异步控制器时,当一个进程正在等待I/O完成时,其线程被释放以供服务器用于处理其他请求。"
所以当第一个远程database_service调用正在处理并等待1秒钟时,线程会返回给IIS ??!!
但是第二个标签计算需要1.5秒钟,这将再次阻塞当前线程1.5秒钟?
所以我释放和阻塞线程,这没有意义,你认为呢?
async
时,不需要使用Task.FromResult
,只需使用return label;
。你的第一个示例中是否意味着不使用async/await
? - Scott Chamberlain