First version
static void Caller()
{
Task<int> test = TestMethod();
int k = test.Result;
Console.WriteLine("k: " + k);
}
In this version the async
keyword would be obsolete. This is a synchronous method. The executing thread blocks at test.Result
until the task has finished.
Second version
static async Task Caller()
{
Task<int> test = TestMethod();
int i = await test;
Console.WriteLine("i: " + i);
}
This is a (kind of) asynchronous version (it's not really asynchron, it's just a synchronous method run on a different thread). The difference to the first version is that the compiler builds a state machine for this.
So the control flow of the executing thread is returned to the caller of this method when await test
is reached.
When the task has finished, the execution of this method is resumed at Console.WriteLine
(or more precisely at the assignment to i
).
For more information about what the compiler does you can read for example this.
The second version is useful if you have a longer running task that you need to execute from an UI. Since the control is returned to the caller while awaiting the task, the UI thread is not blocked and your application stays responsive.