Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Await vs Task.Result in an Async Method [duplicate]

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.

like image 565
luis Avatar asked Aug 27 '15 02:08

luis


People also ask

Should I use result or await?

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

What happens if we execute an asynchronous method but do not await it?

The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.

What is the advantages of async-await approach?

A significant benefit of the async/await pattern in languages that support it is that asynchronous, non-blocking code can be written, with minimal overhead, and looking almost like traditional synchronous, blocking code.

Is an async method that returns task?

Async methods can have the following return types: Task, for an async method that performs an operation but returns no value. Task<TResult>, for an async method that returns a value. void , for an event handler.


1 Answers

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.

like image 132
Frank Fajardo Avatar answered Sep 20 '22 14:09

Frank Fajardo