when we have a call like this:
Database.ExecuteSqlRawAsync(sql, parameters);
we can await it:
await Database.ExecuteSqlRawAsync(sql, parameters);
which is great.
But what is the point of .Result?
Database.ExecuteSqlRawAsync(sql, parameters).Result;
When would this be of any use?
CodePudding user response:
The first case would be when you want to wait synchronously for the result. This is not recommended, due to the potential of deadlocks, but the possibility is available if you really need it.
Another use case is when using something like Task.WhenAll. This does not return a result when awaiting, so you need another way to get to the result of each individual task. Since you are sure all the tasks are completed it does not really matter if you use await task
or task.Result
.
CodePudding user response:
Asynchronous methods return Task
objects (or Task<T>
objects). All Task
objects provide the .Result
property to allow us to wait for tasks to complete synchronously.
Generally you should await tasks instead of using the .Result
property as using .Result
blocks the calling thread.
You can use .Result
if you need to utilise an asynchronous method from a synchronous method/context.
Result
can also be used to access the result of a finished task without blocking the calling thread (e.g. after awaiting a Task.WhenAll call as mentioned by @JonasH).