Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In the article about eliding async await, there is an example as follows:

public Task<string> GetElidingKeywordsAsync(string url)
{
    using (var client = new HttpClient())
        return client.GetStringAsync(url);
}

And he described the flow as follows:

With GetElidingKeywordsAsync, the code does this:

  1. Create the HttpClient object.

  2. Invoke GetStringAsync, which returns an incomplete task.

  3. Disposes the HttpClient object.

  4. Returns the task that was returned from GetStringAsync.

Why isn't the flow as follows?

  1. Create the HttpClient object.

  2. Disposes the HttpClient object.

  3. Invokes the GetStringAsync, and returns the task that was returned from GetStringAsync.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
236 views
Welcome To Ask or Share your Answers For Others

1 Answer

A using block without curly braces or semi-colon has an implied body:

public Task<string> GetElidingKeywordsAsync(string url)
{
    using (var client = new HttpClient())
        return client.GetStringAsync(url); // using body
}

This can be normalized to:

public Task<string> GetElidingKeywordsAsync(string url)
{
    using (var client = new HttpClient())
    {
        return client.GetStringAsync(url);
    }
}

Or written more compactly in C#8.0:

public Task<string> GetElidingKeywordsAsync(string url)
{
    using var client = new HttpClient();
    return client.GetStringAsync(url);
}

If you add a semi-colon, there would be an empty body, yielding the behavior you describe in OP:

public Task<string> GetElidingKeywordsAsync(string url)
{
    HttpClient client;
    using (client = new HttpClient());  // gets disposed before next statement
        return client.GetStringAsync(url);  // don't be fooled by the indent
}

This can be normalized to:

public Task<string> GetElidingKeywordsAsync(string url)
{
    HttpClient client;
    using (client = new HttpClient())
    {
    }
    return client.GetStringAsync(url);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...