Introduction:
There are 3 types of Asynchronous programming model that exists in the dotnet ecosystem.
- Asynchronous Programming Model.
- Event-based Asynchronous Pattern.
- Task-based Asynchronous Pattern.
Among these three, the Task-based model is the recommended approach to achieve asynchrony in dotnet. The rest of the two models are legacy models (deprecated).
What is it?
Task is a construct of promise model of concurrency which means it will offer a promise that whatever work is requested it will be returned with a promise. Task is an abstraction of the work that is happening asynchronously not an abstraction over threading. By default, tasks execute on the current thread and delegate work to the operating system as needed.
In a Task-based asynchronous pattern (TAP) we need to be aware of few things.
Target environment (Async Await signature):
You can start using the Task-based model to your model just returning a Task or Task. It can be used as an asynchronous/synchronous environment. If you want to use it as asynchronous, you have to add the async keyword before that method and make sure it returns a Task. You can return just only a Task or a Task of any other data structure you want. There is a limitation to the asynchronous methods in c#. You cannot use ref or out in your async method.
Cancelation token:
The cancelation token is a very interesting thing in the TAP although it is optional. If you know what it does you will be amazed too. So a cancelation token does cancel your async operation gracefully as the name suggests. If a cancellation token has requested cancellation before the TAP method that accepts that token is called, the TAP method should return a Canceled task. However, if cancellation is requested while the asynchronous operation is running, the asynchronous operation need not accept the cancellation request. The returned task should end in the Canceled state only if the operation ends as a result of the cancellation request.
Task status:
The Task class provides a life cycle for async operations and that cycle is represented by the TaskStatus enum. This task status plays a very important role in every part of the TAP.
Summarize:
- The returned tasks status will be Canceled. The canceled state is meant to be the final state for a task.
- The IsCompleted property should return true when the operation is ended via cancellation.
- If the task has a result (Task) it should be empty and an exception should not be thrown when awaited.
If you really want to know more about TAP head over to the Microsoft documentation here