Waiting vs Task. Result in an Asynchronous Method

What is the difference between doing the following:

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

against

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

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

+7
c # asynchronous amazon-dynamodb async-await task
source share
2 answers

await asynchronously decompresses the result of your task, while just using Result will block until the task completes.

See this explanation from John Skeet.

+16
source share

task.Result gets access to the get accessor property blocks the calling thread until the asynchronous operation is completed; this is equivalent to calling the Wait method. As soon as the result of the operation is available, it is saved and immediately returned on subsequent calls to the Result property. Note that if an exception occurred while the task was running, or if the task was canceled, the Result property does not return a value. Instead, attempting to access a property value throws an AggregateException. The only difference is that the wait will not be blocked. Instead, it will asynchronously wait for the task to complete and resume

+3
source share

All Articles