-1

I have one question about await keyword. Here is some test code:

string username = await GetUsernameAsync();
// Some other code
var some_variable = username;

My question is: Does waiting starts at first line where we called async method or at the third line where we need the result of async method? Does some other code executes after GetUsernameAsync finishes its execution, or they are executing in parallel?

Aleksa
  • 2,976
  • 4
  • 30
  • 49
  • 2
    the waiting will be at the first line – Seb Feb 09 '16 at 15:46
  • This could easily be tested. But basically the execution of these statements halts (waits) at the `await` keyword, as implied by the keyword itself. – David Feb 09 '16 at 15:49

2 Answers2

3

It happens at the line where the await is.

If you want to delay the waiting, move the await to the moment you need the result. Remember the task, and move on. Then if you need the result, await the task:

Task<string> usernameTask = GetUsernameAsync();
// Some other code
var some_variable = await usernameTask;
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
1

The first one. Take into account the await is just sugar syntax. It will be, more or less, replaced by a Task.Wait() to obtain the result. In fact, GetUsernameAsync() will return a Task, not a string.

Take a look to this link to deep more how threads work with the asyn/await pattern

cpsaez
  • 314
  • 1
  • 11