Making Concurrent API calls Asynchronously (Is this Correct?)
Apologies for the long code, need to split it up into 2 posts because it's really long:
6 Replies
make the calls separate. one method should only be doing one thing
you're introducing more complexity here
this is ok (although you could use
var
)
but then this calls are in sequence...
What is the proper way to make them concurrent
your method is somewhat concurrent but it's not optimal
instead you should be using Task.WhenAll
var task1 = client.Foobar();
var task2 = client.Barfoo();
await Task.WhenAll(task1, task2);
// Calling the .Result property is only safe after the Task has been awaited.
Console.WriteLine("Results are: {task1.Result} and {task2.Result}");
this also signals your intent to other developers more clearly
@surwren
unrelated to async, you should avoid creating new httpclient instances in using blocks, as this can lead to socket exhaustion. the better approach is to use a single longlived instance, or look into using IHttpClientFactory
https://learn.microsoft.com/en-us/dotnet/fundamentals/networking/http/httpclient-guidelines
HttpClient guidelines for .NET - .NET
Learn about using HttpClient instances to send HTTP requests and how you can manage clients using IHttpClientFactory in your .NET apps.