0
using System.Net;

Console.WriteLine("start!");

await HttpGetAsync("http://localhost:5203/sleep/5"); // Mock sleep api that will return after 5 seconds.
await HttpGetAsync("http://localhost:5203/sleep/3"); // ... after 3 seconds.

int i = 0;

while (i < 20)
{
    Console.WriteLine(i++);
    Thread.Sleep(100);
}

Console.WriteLine("end!");

Console.ReadKey();

static async Task<HttpStatusCode> HttpGetAsync(string url)
{
    using HttpClient client = new();
    HttpResponseMessage result = await client.GetAsync(url);
    Console.WriteLine(await result.Content.ReadAsStringAsync());

    return result.StatusCode;
}

I got this:

enter image description here

Isn't Task.Run() run in background thread? My expected result is:

0 1 2 ... 20

After 3 second, I'm awake!

After 5 second, I'm awake!

lljxww
  • 23
  • 4
  • 8
    `await` enforces an execution order, i.e. your code states that the first request should run (in the background), when it’s complete start the second request, when it’s complete output the numbers. If you want a different order await later: `var task1 = HttpGetAsync(…); var task2 = HttpGetAsync(…); while (…); await Task.WhenAll(task1, task2);` – ckuri Aug 12 '22 at 07:07
  • 1
    Does this answer your question? [Run a Task, do something and then wait?](https://stackoverflow.com/questions/29125968/run-a-task-do-something-and-then-wait) – Charlieface Aug 12 '22 at 08:20

0 Answers0