简体   繁体   中英

Should async method calls chain up in all method calls scope?

I am writing a asp.net core web API which is consuming another third party API and returning some JSON response back to the caller which will be a client web browser. While writing my implementation in asynchronous manner the visual studio is suggesting to remove async await from my following async methods.

I just wanted to get clarification that i don't need to wrap these two method in async await ?

Following are the methods:

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);       
}

and following is method that is consumed by the above two methods :

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);
}

Following is the suggestion from Visual Studio :

在此处输入图片说明

Async in method declaration and await may be elided

I just wanted to get clarification that i don't need to wrap these two method in async await?

That is correct. You can trust the recommendations made by Visual Studio and ReSharper; they are very conservative in their recommendations.

In this case, because each method just passes arguments to another method and returns the same thing, it is safe toelide the async and await .

However, I wouldn't feel that you have to. Eliding the keywords gives you a (very) minor increase in performance. But if those methods do anything non-trivial - or are changed in the future to do anything non-trivial - then you would want to keep the async / await keywords.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM