Coding Tips & Tricks


Home>C#

C# Parallel Invoke

While working through some code, I noticed a method that I have never seen before. I knew that the .Net 4 Framework had introduced a Parallel Class that helped make parallel ForEach Loops easier, but after some searching I came across the ParallelInvoke() method.

Parallel Invoke .Net 4

So, I jumped on the MSDN site and learnt a little bit more about Task Parallels. It makes running one or more independent tasks concurrently really easy with it's fluent interface. After some reading, I noticed that there are a few benefits that can be gained from running tasks asynchronously. This is taken from the MSDN site:-

More efficient and more scalable use of system resources.

Behind the scenes, tasks are queued to the ThreadPool, which has been enhanced with algorithms (like hill-climbing) that determine and adjust to the number of threads that maximizes throughput. This makes tasks relatively lightweight, and you can create many of them to enable fine-grained parallelism. To complement this, widely-known work-stealing algorithms are employed to provide load-balancing.

More programmatic control than is possible with a thread or work item.

Tasks and the framework built around them provide a rich set of APIs that support waiting, cancellation, continuations, robust exception handling, detailed status, custom scheduling, and more.

So, let's write some code examples! In order to run two tasks concurrently, you need to follow the pattern below.

Parallel.Invoke(() => DoSomeWork(), () => DoSomeOtherWork());

As you can see, the Parallel Library uses a lot of Lambda expressions to define delegates. If you would like more information on Lambda expressions, please read this article.

Before you get started adding any code you will need to add a reference in your project to theSystem.Threading.Tasks library. Next, add the method following the above pattern.

Parallel Invoke

As you can see the three methods will run concurrently, and it was pretty straightforward to implement! For more information on the Task Parallel Library, please check out the MSDN site.








Comments


Add your comment

300 Characters left


Please fill this in to confirm that you are human