user3220670
user3220670

Reputation: 79

Handling multiple synchronous network calls within asynchronous methods?

In the below example, I have a method that is called asynchronously with a flag.

Within the method, it will make two separate network calls asynchronously and await them after both have been called and the result is needed. Once it has the result of both, it will call a method which processes the results of the two network calls one at a time. Each item requires a network call which, for the purposes of this question, can't be made asynchronous and must be awaited immediately.

private HttpClient client = new HttpClient();

static async Task Main()
{
    var task1 = FooAsync(true);
    var task2 = FooAsync(false);

    Task.WaitAll(Task1, Task2);

    // Do some stuff with the results
}

private async Task<List<int>> FooAsync(bool input)
{
    HttpResponseMessage response1 = client.GetAsync("https://baseUrlX/" + input.ToString());
    HttpResponseMessage response2 = client.GetAsync("https://baseUrlY/" + input.ToString());

    string content1 = await response1.Content.ReadAsStringAsync();
    string content2 = await response2.Content.ReadAsStringAsync();

    return ProcessItems(content1, content2);
}

private async Task<List<int>> ProcessItemsAsync(string content1, string content2)
{
    List<int> results = new List<int>();
    string content = content1 + content2;
    foreach(char c in content)
    {
        var response = client.GetAsync("https://someUrl/" + c);
        string content = await response.Content.ReadAsStringAsync(); // Blocking call here
        results.Add(Int.Parse(content));
    }

    return results;
}

My question is whether the two asynchronously calls in Main() accomplishes anything or if they would be processed synchronously. Are there two independent threads fired from there that fire off two more independent threads inside FooAsync before processing each item in ProcessItems using the two original threads?

Upvotes: 1

Views: 362

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 456467

My question is whether the two asynchronously calls in Main() accomplishes anything or if they would be processed synchronously. Are there two independent threads fired from there that fire off two more independent threads inside FooAsync before processing each item in ProcessItems using the two original threads?

Asynchrony has very little to do with threads. When working with async, it's better to adopt the asynchronous mentality (intro; best practices) rather than thinking of how they're related to threads.

The two FooAsync calls will be processed concurrently, and each of them will make two concurrent HTTP calls.

Side note: it is normal to do async all the way, rather than blocking on async code. So the code in Main would be more naturally expressed using await Task.WhenAll(Task1, Task2); rather than Task.WaitAll(Task1, Task2);.

Upvotes: 2

Related Questions