Parallel Programming Simple Design

When a developer really wants to get the most out of performance they look to using the power of multithreading.  .NET and C# make this very easy to do.  I wanted to give a simple design overview of an application that will utilize Parallel Programming features in C#.

I first started doing an overview of the debugging features for concurrent programming in Visual Studio, but found a great overview here: MSDN: Debug Multithreaded Applications in Visual Studio

I will walk through how to refactor a loan processing application to utilize concurrent features starting from what I would consider “normal” code. 

Initial Code

This is fairly standard looking code, extremely simplified of course.  Currently running this code will output the execution time:
Processed 500 loans, taking 28.1034711 seconds

The first thing you need to do, and should’ve already been done is refactoring this code.  We need it separated into simple cohesive methods that are both easy to read and identify what is being done.  The reason I wanted to point this out is that properly structured code makes Parallel design much simpler.

Refactored Code

This is not a significant difference, but it really shows how much easier refactored code is to read and understand.

Since this is aimed at beginners, I want to stay focused on using the Parallel class methods.  These are very simple to pick up and use.

Since we already have a foreach statement, the easiest method to use is the Parallel.ForEach.  Since the foreach is already scoped, its a natural upgrade.  You will need to worry about any variables that are impacted that are declared and used out of scope.  Can this be moved inside the scope, if not, would this cause a “Race Condition“?  Also does the execution order matter?  If you are unsure about all of this, then you probably either keep refactoring, or realize that executing this in Parallel is not going to work, at least not consistently.

Using Parallel.ForEach

With that simple upgrade, this now has an execution time of:
Processed 500 loans, taking 6.1650105 seconds

Talk about an incredible return of investment!

Finally, we can go a little further, make additional refactors, and follow more of the Unit of Work pattern by chunking out the retrieval and processing of loans in separate pages using the Parallel.For method.

Using Parallel.For && Parallel.ForEach

The execution time has only improved to be:

Processed 450 loans, taking 5.7291776 seconds

Probably not worth the effort, at least not in this small sample, but you can see with these simple upgrades you can turn some slow chugging code into a lean machine.  I would recommend playing around with these tools, and always giving it a try.  Always measure the execution time and don’t forget to run your unit tests!


Leave a Reply

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