In this code snippet, we will take a look at the TPL(Task Parallel Library) in C#.
If you read some of my other posts on threading you will know that it can be quite complicated and laborious for the developers to implement parallelism into their programs(deadlocks, cancellation, thread pooling, getting data back from the thread, …). The Task Parallel Library(TPL) takes care of a lot of these things and or makes them easier to manage.
The TPL uses a thread pool so you don’t have to worry about using it.
The .NET runtime will also automatically decide how many threads it should create. The fact that this is automatic is great because if you don’t create enough threads your application won’t run as fast as it possibly could. While creating too many threads can actually slow down your application(too much context switching).
A task can be thought of as a representation of a piece of code(code block). Multiple instances of a task can be made and run in parallel.
For simple things, for example: looping through an array with a 100 entries, you shouldn’t use multithreading as it just increases the complexity of your code and won’t offer much performance gain(might even decrease it if used improperly).
Let’s have a look at the code below to see how to use the task parallel library.