Parallel Programming Controlling

From my previous post on Parallel Programming, I showed how to simply improve performance by using a Parallel loop.  However, sometimes you need to control those Parallel loops due to limited resources, or maybe you’re calling an external source that has limited connections, such as sockets, and we don’t want to be a bad consumer and make 50 connection calls instantly due to our Parallel loops.  There are a couple things that I wanted to discuss to help with this control.

Initial Parallel Loop:

Output:

DefaultOutput

 

1. Max degree of parallelism

By default the Parallel loop will up as many threads that it can, based on how many cores on the executing computer.  By providing a value for MaxDegreeOfParallelism, you will limit the number of concurrent execution.  By creating a ParallelOptions object, and setting this value, the signature changes slightly:

2. Cancellation

Excepting an external source cancellation is something that you’ll be doing especially on an application that allows user input.  I have an example that is easy to follow, and shows the end result.

Output:

CancelledOutput

 

 

Hopefully these two examples show you a little of what you can do to control your Parallel code and sleep better at night!

 

Leave a Reply

Your email address will not be published. Required fields are marked *