【发布时间】:2014-07-29 06:25:21
【问题描述】:
如何将这个同步方法调用链转换为异步(使用 async/await 运算符)?鉴于只有最后一个调用 DoRequest() 是需要时间执行的调用,那是唯一需要变为异步的方法吗?或者链中的所有调用者,RequestSomething() 和 Process(),是否也需要异步?
[HttpGet]
void Process()
{
var url = "http://someapi.com";
var myObject= RequestSomething(url);
//do something with the myObject.
}
MyObject RequestSomething(string url)
{
var request = new HttpRequestMessage(HttpMethod.Get, url);
var response = DoRequest(request);
return JsonConvert.DeserializeObject<MyObject>(response);
}
//method that takes time to return.
HttpResponseMessage DoRequest(HttpRequestMessage request)
{
var client = new HttpClient();
return client.SendAsync(request).Result;
}
【问题讨论】:
-
RequestSomething什么都不做。仅调用一个方法来返回其结果不会增加任何内容。您可以完全删除它。而Process所做的只是调用一个方法并忽略返回值。你真的需要这两种方法吗? -
这些位于我项目的不同层...我只是将它们放在一起以保持简单。
-
@Servy 我已经更新了我的问题以澄清我在问什么。
-
确保你遵守约定,你的方法被称为
ProcessAsync、RequestSomethingAsync和DoRequestAsync尊重。
标签: c# .net asynchronous async-await