异步方法调用是否应该在所有方法调用范围内链接?

问题描述 投票:2回答:1

我正在编写一个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的建议:

enter image description here

可以取消方法声明中的异步和等待

c# asp.net-core async-await asp.net-core-2.2 .net-core-3.1
1个回答
4
投票

我只是想澄清一下,我不需要在异步等待中包装这两种方法?

是的。您可以信任Visual Studio和ReSharper提出的建议。他们的建议非常保守。

在这种情况下,因为每个方法仅将参数传递给另一个方法并返回相同的内容,所以对于elide the async and await是安全的。

但是,我不会觉得你必须。省略关键字会使您的性能(非常)提高。但是,如果这些方法做了不平凡的事情-或将来更改为不平凡的事情-那么您将希望保留async / await关键字。

© www.soinside.com 2019 - 2024. All rights reserved.