Task Parallel Library (Tasks) and the GUI thread

With .Net 4 we have a very nice feature called the task parallel library.
Especially in long running applications (like database accesses, mathematical computations…) you have to run them on a different thread.

Before .Net 4 we either used the BackgroundWorker or a Thread (from the ThreadPool).

In the good old days we have even been happy with them but when you see the new tasks then you will not like them anymore 😉
With the tasks you can do much more than just running a piece of code in a worker thread but it does not guarantee that the task is not run in the GUI thread.

If that happens it can block the application which could be really annoying for us and also for the user.

In order to guarantee that the task is run in a non GUI thread we have to build our own TaskScheduler.
In the samples for the parallel programming with .net 4 is already a custom TaskScheduler (called StaTaskScheduler) http://code.msdn.microsoft.com/ParExtSamples

Usually you start your task like in this example

Task.Factory.StartNew(() => DoLongRunningOperation());

If you want to use the custom TaskScheduler (called StaTaskScheduler) then you have to start the task like in the following example

var scheduler = new StaTaskScheduler(5);
Task.Factory.StartNew(() => DoLongRunningOperation(),

Now we have a way in which we can be sure that our tasks are not run in the GUI thread.

With the number (5 in my example) we can define how much threads should be used by the TaskScheduler to execute our actions.

If there are not enough threads (ex. if we have 5 tasks and just 2 threads) then the tasks will automatically wait until a thread is free.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: