The correct way to create an asynchronous method

Is the async method used correctly, where the method code must make several asynchronous calls to wait. The plan is to run a few of this method and wait for them to complete before the code continues.

    public static Task<string> Get(string url)
    {
        return Task.Run(async () =>
        {
            var client = getBaseHttpClient();
            var result = await client.GetAsync(url).ConfigureAwait(false);
            if (result.IsSuccessStatusCode)
            {
                return await result.Content.ReadAsStringAsync();
            }
            return null;
        });
    }
+4
source share
1 answer

Your code:

  • starts thread threadpool ( Task.Run),
  • which will start the asynchronous I / O operation ( GetAsync) and then return to the thread pool.
  • When I / O is done ( await), another thread stream ( ConfigureAwait(false)) will be started ,
  • which will start another asynchronous I / O operation to read the contents of the HTTP ( GetAsStringAsync) response and return to threadpool.
  • - (await), , .

1. . , , - getBaseHttpClient threadpool, , , - / .

public static async Task<string> Get(string url)
{
    var client = getBaseHttpClient();
    var result = await client.GetAsync(url).ConfigureAwait(false);
    if (result.IsSuccessStatusCode)
    {
        return await result.Content.ReadAsStringAsync();
    }
    return null;
}

:

var tasks = urls.Select(Get);
var responses = await Task.WhenAll(tasks);
+8

All Articles