C#中将一系列同步方法转换为异步方法

Pra*_*bhu -2 .net c# asynchronous async-await

如何将此同步方法调用链转换为异步(使用 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;
}
Run Code Online (Sandbox Code Playgroud)

Sco*_*ain 5

要正确执行异步操作,它是“具有感染力的”,如果您在一个位置执行此操作,则需要在调用链上一直执行此操作才能从中获得任何真正的好处。因此,无论调用什么,Process()都需要Process通过等待它或像DoRequest这样将其传递到链上来处理从它返回的任务。

async Task Process()
{
   var url = "http://someapi.com";
   var myObject= await RequestSomething(url);
   //do something with the myObject.
}    

async Task<MyObject> RequestSomething(string url)
{
   var request = new HttpRequestMessage(HttpMethod.Get, url);
   var response = await DoRequest(request).ConfigureAwait(false);
   return JsonConvert.DeserializeObject<MyObject>(response);
}

//method that takes time to return.
Task<HttpResponseMessage> DoRequest(HttpRequestMessage request)
{
    var client = new HttpClient();
    return client.SendAsync(request);
}
Run Code Online (Sandbox Code Playgroud)

因为您在执行请求后没有做任何额外的工作,所以您的DoRequest函数中不需要 async/await ,但其他函数将需要 async/await 关键字。这.ConfigureAwait(false)使得该函数不必在 UI 线程上运行其其余代码,这可以为您带来小的性能提升。我不知道代码是否//do something with the myObject.需要你在 UI 线程上,所以我没有把它放在等待上,但如果你不需要在 UI 线程上,你也可以在那里添加它。