Return tasks don't await?


Here we have a simple synchronous operation lies on the service layer that adds announcement and detail in their own contexts.
Where It is called on handler. As you notice we are not awaiting here and simply just returning a task.
This underlined code doesn’t create a state machine. For those of you unfamiliar of state machine.
State machine is in async/await is just a little compiler-generated object that remembers "where to resume" after an async call finishes.
So this happens when we await our task and it created this state machine. On this example take a loot at the compiler generated. (This is when we peek our code with ILSPY) this is IL instruction translated to c#)
I’ve wrote an article previously that might help you understand this: 10 steps that's happening when you await a task.
Also one thing you need to be wary is how exceptions work when using asynchronous programming.
Now here i added an async key here also added an await task delay for the sake of example.
Downside when we don’t await our tasks? CATCHING EXCEPTIONS!
And then on the handler we are going to try to catch the exceptions by not awaiting.
Result = This doesnt catch the exception thrown on the service layer!
We need to await the task before catching exceptions.
Regarding the benchmarks you can read / watch more here: Unfortunately in the c# realms this topic is still under a long debate if it has a huge impact or not. But one thing is for sure. Knowing and participating on this is beneficial.
https://perfaddict.net/await-vs-return-task/
https://www.youtube.com/watch?v=Q2zDatDVnO0&t=406s
https://www.reddit.com/r/csharp/comments/1flc8q2/returning_a_task_vs_asyncawait/
On my conclusion do we really need to just return a Task and not await every Task? It depends on your preference and architecture. Do you want to catch exceptions on that layer? do you want the benefit of your task not creating the state machine?
Again software development is an abstraction , everything has a tradeoffs. Whether it’s readability, performance , etc. But one thing is for sure knowing things work will surely not hurt.
Subscribe to my newsletter
Read articles from Juan Miguel Nieto directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Juan Miguel Nieto
Juan Miguel Nieto
A software developer trying to write organic blogs.