Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net Core Razor components: await vs .Result

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?

like image 303
user2341923 Avatar asked Dec 17 '22 22:12

user2341923


2 Answers

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.

like image 90
Janus Pienaar Avatar answered Dec 20 '22 11:12

Janus Pienaar


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.

like image 38
Nathan White Avatar answered Dec 20 '22 13:12

Nathan White