【发布时间】:2015-11-25 18:40:33
【问题描述】:
假设我有一个控制器操作不能异步(由于各种原因),但我有一个服务(通过多种方法)使用HttpClient 调用休息服务。使用异步客户端和使用.Wait 或.Result 有什么好处吗?还是使用同步方式会不会性能更差?
所以要么:
//MyController.cs
public ActionResult GetSomething(int id)
{
//lots of stuff here
var processedResponse = _myService.Get(id);
//lots more stuff here
return new ContentResult(result);
}
//MyService.cs
public ProcessedResponse Get(int id)
{
var client = new HttpClient();
var result = client.Get(_url+id);
return Process(result);
}
或者:
//MyController.cs
public ActionResult GetSomething(int id)
{
//lots of stuff here
var processedResponse = _myService.GetAsync(id).Result;
//or, .Wait, or Task.Run(...), or something similar
//lots more stuff here
return new ContentResult(result);
}
//MyService.cs
public async Task<ProcessedResponse> GetAsync(int id)
{
var client = new HttpClient();
var result = await client.GetAsync(_url+id);
return await Process(result);
}
【问题讨论】:
-
IMO,创建服务方法
async的唯一原因是计划将控制器操作重写为async。 -
@Marius:很想知道阻止异步控制器的“各种原因”是什么。
标签: c# asp.net asynchronous async-await