0

I've been reading about the use of async-await and there's one concept I'm not really sure I quite understood because most of the examples consider what happens to the execution of the calling method and not the actual async method.

Suppose I have this piece of code

...
var r1 = await httpClient.GetAsync(url1);
var r2 = await httpClient.GetAsync(url2);
...

Will the second GET request for url2 be executed only after content of url1 has been downloaded or can it be executed also before content of url1 is downloaded?

In other words, will the following code call both URLs at the same time without waiting for the first one to finish and the "waiting" only happens at the await r1/await r2 lines?

...
var r1 = httpClient.GetAsync(url1);
var r2 = httpClient.GetAsync(url2);

var response1 = await r1;
var response2 = await r2;
...

Lastly, can you confirm that there is a difference between these 2 pieces of code I provided?

Thanks

leopik
  • 2,323
  • 2
  • 17
  • 29
  • 1
    Yes, that's exactly what await is for. I recomment this article from Lippert : https://msdn.microsoft.com/en-us/magazine/hh456401.aspx.It look long but it's a help in understanding away and async – Drag and Drop May 22 '18 at 12:13
  • And once you got addicted you can find more here: https://blogs.msdn.microsoft.com/ericlippert/tag/async/. From your best provider of C# lesson Lippert – Drag and Drop May 22 '18 at 12:15
  • @DragandDrop That first link is dead – Daan May 22 '18 at 12:18
  • 1
    @Daan there is a space missing at the end of the link so there is an `.it` that should not be there : https://msdn.microsoft.com/en-us/magazine/hh456401.aspx More than ( 5minute can't edit) – Drag and Drop May 22 '18 at 12:19
  • If you were the thread and your name is `T1`, here is what `await` means "T1: hey threadpool, ask one of your threads to do this and do not continue forward. Let me know once this is done. I am leaving because I need to something else." Sometime later, you are somewhere else but you will be interrupted. "PoolThread: Hey T1, I am done". You start exécution of the next line of code and notice it is another `await` and thus you say the same thing. It is not always a thread from the pool, but in most cases it is. – CodingYoshi May 22 '18 at 12:32
  • But it is not important how it is implemented and you should not bother with it, unless you need to. – CodingYoshi May 22 '18 at 12:35
  • @CodingYoshi For `await` its not mandatory that a Threadpool thread is required, it can be a Threadless operation for pure IO call using IO completion ports, which is the main use case for Async-Await. Thread Pool comes in the picture for in Memory / CPU bound operation, where something like `Task.Run`is awaited – Mrinal Kamboj May 23 '18 at 06:36
  • @mrinalkamboj Correct and I mentioned that in the last sentence in my comment. – CodingYoshi May 23 '18 at 10:10

0 Answers0