【问题标题】:Should async method calls chain up in all method calls scope?异步方法调用是否应该在所有方法调用范围内链接起来?
【发布时间】:2020-05-27 20:19:39
【问题描述】:

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

方法声明中的异步和等待可能被省略

【问题讨论】:

  • 在某一时刻,他们正在考虑使用编译器automatically remove these。由于一些与异常处理有关的原因,它没有完成。如果您甚至没有考虑过这里的例外情况,那么您没有理由不考虑。
  • eliding async / await的优缺点。
  • @EhsanSajjad 你不需要包装它们。由于这些方法(GetAsyncPostAsync)只是传递,并且其中没有调用其他方法,因此您可以删除 async-await 并返回任务
  • @EhsanSajjad 是正确的。您应该查看上面由 Johnathan Barclay 链接的文章
  • @EhsanSajjad 我总是尊重这个参考 Async/Await - Best Practices in Asynchronous Programming 并对该主题表示遗憾

标签: c# asp.net-core async-await asp.net-core-2.2 .net-core-3.1


【解决方案1】:

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

没错。您可以相信 Visual Studio 和 ReSharper 提出的建议;他们的建议非常保守。

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

但是,我认为您必须这样做。删除关键字可以(非常)轻微地提高性能。但是,如果这些方法做了不重要的事情——或者在未来发生了改变以做不重要的事情——那么你会想要保留 async/await 关键字。

【讨论】:

  • 感谢@Stephen,但您对 ConfigureAwait 的建议有何建议,在基于 .NET 核心的 API 中是否仍需要它?
  • @EhsanSajjad:我仍然推荐ConfigureAwait(false) 用于通用库。如果你使用的是 ASP.NET Core,那么you don't need to use it
猜你喜欢
  • 2016-12-26
  • 2018-05-15
  • 1970-01-01
  • 1970-01-01
  • 2020-12-19
  • 2016-02-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多