C# TPL(Task Parallel Library) And Tasks

C# Code Snippets TPL(Task Parallel Library) and Tasks
Share:

About

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.

For example:

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.

Note:
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.

Code:

Resulting output:

Exception thrown by the cancelation token
Share:

Leave a Reply

Your email address will not be published.

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger