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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With