You can think that by the await
keyword you are immediately returning a Task
(or similar) instead of the actual value (see my similar answer on JS). We must return a Task
or similar since the actual return value is probably not known yet...
To illustrate the returning to the caller, here's the example from my other answer translated to C#:
class Program
{
static async Task<string> MyAsyncFunc()
{
int i;
for( i = 0; i < 1000000; i++ ) ; // create some synchronous delay
// Create an asynchronous task that we can await on later...
var innerTask = ( ( Func<Task<string>> )( async () => {
await Task.Delay( 1000 );
return "done!";
} ) )();
Console.WriteLine( "message inside f before returning, still synchronous, i = " + i );
// let's await and at the same time return a Task to the caller
var result = await innerTask;
Console.WriteLine( "message inside f after await, asynchronous now" );
Console.WriteLine( result ); // "done!"
return "function finished";
}
static void Main()
{
var myresult = MyAsyncFunc();
Console.WriteLine( "message outside f, immediately after calling f" );
System.Threading.Thread.Sleep( 2000 ); // Create delay to prevent exit before asynchronous writing of lines.
}
}
The corresponding output is:
message inside f before returning, still synchronous, i = 1000000
message outside f, immediately after calling f
message inside f after await, asynchronous now
done!
Note that Main()
already continues executing after the function call well before the actual return value "function finished"
is returned.