Reputation: 9360
I do not understand , i have seen that there are many methods provided by the .Net Framework
that have both async
and non-async
variants.
My question is what advantage does an async
method provide me given the following constraints:
- I will not fetch the Task.Result
multiple times in the same method
- I am not using CPU-bound
tasks (Task.Run(...)
)
I am in a MVC
controller and i want to process a post
request:
[HttPost]
[Route(..)]
public async Task DoSomething(MyModel model)
{
var asyncResult=await NETMethodAsync(model); //PostAsync,WriteAsync....
var nonAsyncResult= NETMethod(model); //Post,Write,....etc..
return result;
}
In this case i will use the result
only once in my method and i will not demand it multiple times ( where await
would just give me the completed task-result) what is the difference ?
I am basically creating a StateMachine
in my MethodAsync
for what?
I could do the operation non-async
faster i suppose.
If i am not delegating the method on a separate Task
(like below) why would i use the async
version ?
I am asking because even the MVC Controller
templates by default provide all CRUD
operations using the async
versions.
Task tsk=Task.Run(async()=> await MethodAsync() );
P.S In my scenario is it something that i missed.Is it faster to use the async
(that internally spins a state-machine) ,then the non-async version ?
Upvotes: 2
Views: 3101
Reputation: 456342
what is the difference?
Scalability. Specifically, synchronous methods block the calling thread, and asynchronous methods do not.
What this means (for an ASP.NET application) is that synchronous action methods block the request thread for the duration of the request, and that asynchronous action methods do not block that thread.
This, in turn, yields greater scalability. Since the thread pool is a limited resource (and in particular, since it has a limited thread injection rate), asynchronous code allows your app to handle greater load with fewer threads.
For more information, see the "Synchronous vs. Asynchronous Request Handling" section in my article on async ASP.NET; that section of the article applies to all server technologies, including ASP.NET Core. You can also check out this gist which demonstrates the scalability difference by limiting the thread pool growth rate. I haven't ported that example to ASP.NET Core, but it should be straightforward to do.
Upvotes: 12