我正在编写一个asp.net核心Web API,它正在使用另一个第三方API,并将一些JSON响应返回给将作为客户端Web浏览器的调用者。在以异步方式编写实现时,Visual Studio建议从以下异步方法中删除异步等待。
我只是想澄清一下,我不需要在异步等待中包装这两种方法?
以下是方法:
public async Task<T> GetAsync<T>(string url)
{
return await GetResponse<T>(HttpMethod.GET,url);
}
public async Task<T> PostAsync<T>(string url, object payload)
{
return await GetResponse<T>(HttpMethod.POST, url,payload);
}
以下是上述两种方法消耗的方法:
public async Task<T> GetResponse<T>(HttpMethod method,string url, object payload = null)
{
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
HttpResponseMessage response;
switch (method)
{
case HttpMethod.POST:
{
var content = new StringContent(payload.ToString(), Encoding.UTF8, "application/json");
response = await client.PostAsync(url, content).ConfigureAwait(false);
break;
}
case HttpMethod.GET:
default:
method = HttpMethod.GET;
response = await client.GetAsync(url).ConfigureAwait(false);
break;
}
var responseMessageString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
_logger.LogInformation($"{method.ToString()} {method.ToString()} {Environment.NewLine} Response: {responseMessageString}");
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(responseMessageString);
}
以下是Visual Studio的建议:
可以取消方法声明中的异步和等待
我只是想澄清一下,我不需要在异步等待中包装这两种方法?
是的。您可以信任Visual Studio和ReSharper提出的建议。他们的建议非常保守。
在这种情况下,因为每个方法仅将参数传递给另一个方法并返回相同的内容,所以对于elide the async
and await
是安全的。
但是,我不会觉得你必须。省略关键字会使您的性能(非常)提高。但是,如果这些方法做了不平凡的事情-或将来更改为不平凡的事情-那么您将希望保留async
/ await
关键字。