Royi Namir
Royi Namir

Reputation: 148694

Async and await may be elided?

I have this simple code :

 public async  Task<string> GetAsync()
   {
      var httpClient = new HttpClient();
      return await httpClient.GetStringAsync("...");
   }

However Resharper says :

enter image description here

This warning is gone when I use a variable :

 public async  Task<string> GetAsync()
        {
            var httpClient = new HttpClient();
            var st = await  httpClient.GetStringAsync("...");
            return st;
        }

I already know the danger when doing

 using (var httpClient = new HttpClient())
 return  httpClient.GetStringAsync("...");

(Task will be canceled)

But that's not my case here since I'm using await ( and not using using).

Question:

Why does Resharper warn me?

Upvotes: 2

Views: 1288

Answers (1)

V0ldek
V0ldek

Reputation: 10613

Your method "can" be rewritten as follows:

public Task<string> GetAsync()
{
    var httpClient = new HttpClient();
    return httpClient.GetStringAsync("...");
}

thus avoiding the overhead of compiling an async method and then doing a costly control flow switch with await. The functionality is still the same. That's what R# is telling you about - you can omit the async/await and avoid an unnecessary overhead.

However, I put the "can" in quotes, as your code is smelly, because first of all, HttpClient is an IDisposable, so you should dispose of it after usage. Then the async/await will be necessary:

public async Task<string> GetAsync()
{
    using(var httpClient = new HttpClient())
    {
        return await httpClient.GetStringAsync("...");
    }
}

since this will be translated into an equivalent of

public async Task<string> GetAsync()
{
    var httpClient = new HttpClient();
    var result = await httpClient.GetStringAsync("...");
    httpClient.Dispose();
    return result;
}

This one you absolutely should fix. Secondly, a thing to consider is that creating HttpClients can silently destabilise your app, as HttpClients should be reused. See this blog post and this SE Stack Exchange post.

Upvotes: 5

Related Questions