- Featured post
C# Task async programming (TAP) and parallel code
The core for asynchronous programming are the objects Task
and Task<T>
. Both of them are compatible with the keywords async
and await
.
First of all we need to identify if the code’s I/O-bound or CPU-bound.
- the code’s limited for external operations and waits for something a lot of time. Examples of this are DDBB calls, or a server’s response. In this case we have to use
async
/await
to free the thread while we wait - the code does a CPU-intensive operation. Then we move the work to another thread using
Task.Run()
so we don’t block the main thread.
async code vs parallel code
(!) Asynchronous code is not the same as parallel code (!)
- In async code you are trying to make your threads do as little work as possible. This will keep your app responsibe, capable to serve many requests at once and scale well.
- In parallel code you do the opposite. You use and keep a hold on a thread to do CPU-intensive calculations
async code
The importante of async programming is that you choose when to wait on a task. This way, you can start other tasks concurrently
In async code, one single thread can start the next task concurrently before the previous one completes.
(!) async
code doesn’t cause additional threads to be created because an async
method doesn’t run on its own thread. (!) It runs on the current synchronization context and uses time on the thread only when the method is active.
parallel code
For parallelism you need multiple threads where each thread executes a task, and all of those tasks are executed at the same time