Is the following the correct way to make a async method, where the code in the method have to do multiple async calls that needs to be waited on. The plan is to start multiple of this method, and when wait for all of them to finish 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;
});
}
Your code:
Task.Run
),GetAsync
), and then go back to the threadpool.await
), another threadpool thread will be started (ConfigureAwait(false)
), GetAsStringAsync
), and go back to the threadpool.await
), another threadpool thread will be started to return the content to the calling method.You could skip step 1. altogether. All it does is defer the call to getBaseHttpClient
to a threadpool thread, which I'll assume is not intensive CPU-bound work - in which case, it could/should be done synchronously.
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;
}
Calling code would be:
var tasks = urls.Select(Get);
var responses = await Task.WhenAll(tasks);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With