Sunday, 1 September 2013

Task with the keyword 'await'

Task with the keyword 'await'

So I'm curious about Task<T>'s behaviour when it is used with await.
I made this very simple method:
private Task<int> Foo()
{
// Do some heavy work.
System.Threading.Thread.Sleep(4000);
// Always return int(5000).
var Result = Task.Run(() => { return 5000; });
return Result;
}
And I found I could get two different results from how I invoke Foo().
// Return System.Threading.Tasks.Task<int>.
// So I have to use Result.Result to get int(5000).
var Result = Foo();
// Return directly int(5000).
var BetterResult = await Foo();
So what does the compiler exactly do internally, when await is used? Why
do I not have to use the Result property when await is there, and I do
without await?
Thanks in adavance.

No comments:

Post a Comment