Limit parallel execution in TAP

Limit parallel execution in TAP

Did you ever want to limit the parallel execution of a task, when using task-based asynchronous pattern in c#?

In the next few step I guide you through the creation of a TaskScheduler that will enable you exactly that.

The Scenario

You need to limit parallel execution of tasks that are started. You need to be able to limit the execution only for certain tasks.

The Basics

The .Net Framework offers a technology called Task-based Asynchronous Pattern. This pattern allows you to parallelize operations in a very simple way and automatically deals with the different schedulers that are used during runtime. For example it’s possible to use the await keyword to launch a long running operation from the main¬†UI thread. And wait for the task and continue with your code scheduled back to the main UI thread.

In the back the TAP makes use of different TaskSchedulers but for our example we’re going to implement our own to limit parallel execution of the different queued Tasks.

The Code

So here is the code. Feel free to use it in your projects, just drop a comment.

What’s it all about?

It’s pretty simple we have multiple methods we override, a property that handles the currently alowed degree of parallelism and Some fields that hold the current state of the scheduler. The code is pretty much self explainatory.

The ThreadStatic at the top is a marker if the current ThreadPool thread is processing items. The Tasks get queued into a LinkList called m_Tasks. And there is a counter for how many delegates are there. The constructor takes one argument and sets the degreee of parallelism.

The linked list is also used as a lock for the synchronization of the work balancing.

Why limit parallel execution of Tasks?

In my next Post I’m going to show you a useful example that needs limit parallel execution.