Await vs Task.Result in an Async Method

C#AsynchronousAsync AwaitTaskAmazon Dynamodb

C# Problem Overview


What's the difference between doing the following:

async Task<T> method(){
    var r = await dynamodb.GetItemAsync(...)
    return r.Item;
}

vs

async Task<T> method(){
    var task = dynamodb.GetItemAsync(...)
    return task.Result.Item;
}

In my case, for some reason, only the second works. The first one never seems to end.

C# Solutions


Solution 1 - C#

await asynchronously unwraps the result of your task, whereas just using Result would block until the task had completed.

See this explanantion from Jon Skeet.

Solution 2 - C#

task.Result is accessing the property's get accessor blocks the calling thread until the asynchronous operation is complete; it is equivalent to calling the Wait method. Once the result of an operation is available, it is stored and is returned immediately on subsequent calls to the Result property. Note that, if an exception occurred during the operation of the task, or if the task has been cancelled, the Result property does not return a value. Instead, attempting to access the property value throws an AggregateException exception. The only difference is that the await will not block. Instead, it will asynchronously wait for the Task to complete and then resume

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionluisView Question on Stackoverflow
Solution 1 - C#Frank FajardoView Answer on Stackoverflow
Solution 2 - C#NASSERView Answer on Stackoverflow