140

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.

2

2 Answers 2

156

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.

Sign up to request clarification or add additional context in comments.

9 Comments

why is await not working in this case though, but Result does work
@luis: Lacking any other information, the only answer I see to that is that it's not actually working in the await case. You just mistakenly think it does because the method itself returns. But the task being awaited likely does not complete either way. If you want an answer to that (which is a different question than the one you asked), you need to post a new question, stating that clearly, and providing a good, minimal, complete code example that reliably reproduces the problem.
Calling Result bare is a hidden deadlock.
@user2953241: .Result or all of its possible variants cause a threadpool thread to wait for a job on the thread pool to finish. This can exhaust all threads on the threadpool leaving none to perform the actual work.
@PedroMachado The point is that .Result causes the current thread to block and wait for the result. await allows the current thread to go off and be useful doing other work while the result is being produced.
|
38

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

3 Comments

why is await not working in this case though, but Result does work
Calling Result bare is a hidden deadlock.
Piggybacking off of Joshua, you can find out more about why it causes a hidden deadlock here: stackoverflow.com/questions/17248680/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.