5

Consider the following two lines in View file for ASP.Net Core:

    @Component.InvokeAsync("Greeting").Result
    @await Component.InvokeAsync("Greeting")

What is the difference? Which is preferable and in which situation? In my code they both give the same visual result; are there cases where results could be different?

user2341923
  • 4,537
  • 6
  • 30
  • 44
  • Possible duplicate of [Await on a completed task same as task.Result?](https://stackoverflow.com/questions/24623120/await-on-a-completed-task-same-as-task-result) – rickvdbosch Jun 18 '18 at 12:55

4 Answers4

5

Both calls most likely takes the same time to return, the difference is that the first call will block the thread but the second call will return the thread to the pool and allow it to be used by another request. Essentially meaning that your Service can handle more requests per second when using the await keyword.

Use await where possible to prevent the thread from blocking. Do some reading on async and await - https://learn.microsoft.com/en-us/dotnet/csharp/async

From MSDN - The await keyword is where the magic happens. It yields control to the caller of the method that performed await, and it ultimately allows a UI to be responsive or a service to be elastic.

Essentially the await keyword yields control back to the caller and releases the thread back into the threadpool.

Janus Pienaar
  • 1,083
  • 7
  • 14
4

Calling .Result will result in a blocking call which could cause issues with your UI. If you're calling an asynchronous function, you should await it to allow the rest of your application to continue without being blocked.

Nathan White
  • 1,082
  • 7
  • 21
3

NB: Razor Components are something different - this is server-side hosted Blazor, part of .NET Core 3.0. What you mean, however, is ASP.NET Core x.x View Components.

Alexander Christov
  • 9,625
  • 7
  • 43
  • 58
1

Calling .Result on the component makes you lose the essence of the await which is suppose to prevent blocking your UI as the code does not need to wait for the complete execution of the Razor component.

Hence it is advisable not to call the .Result rather you should await the result to allow the complete asynchronous execution flow of your code.

Codemasta
  • 111
  • 4