2

I writing a small example to get value 5 in method TestMethod, I have 2 ways to do that:

    static async Task<int> TestMethod()
    {
        await Task.Delay(0);
        return 5;
    }

    static async Task Caller()
    {
        Task<int> test = TestMethod();
        int i = await test;
        Console.WriteLine("i: " + i);

        int k = test.Result;
        Console.WriteLine("k: " + k);
    }

The output:

i: 5

k: 5

So, my questions are: what's the difference between await test and test.Result? And when to use await test/test.Result?

Tân
  • 1
  • 15
  • 56
  • 102

2 Answers2

6

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.

René Vogt
  • 43,056
  • 14
  • 77
  • 99
1

Task.Result is equivalent to Task.Wait Method which blocks synchronously until the task is complete.

await on the other hand waits asynchronously till the task is completed.

If you can await is better.

Nitin
  • 18,344
  • 2
  • 36
  • 53