Parallel Programming

Many programmers today are not taking full advantage of all the hardware available on modern computer systems. A typical modern computer has at least 4 CPU cores that can perform simultaneous processing, while programmers tend to write synchronous, single-threaded code. There’s a reason: writing multi-processing or multi-threading code is difficult to write correctly.

Microsoft has given us some wonderful language features that make multi-threaded code easier to write. These include the Task class and the async and await keywords in our .Net languages. So we have been given some very powerful tools. How do we actually incorporate these into the programs we write?

A whitepaper has been written by a gentleman named Stephen Toub, a Microsoft employee, named Patterns of Parallel Programming. The link allows you to download a version for either C# or Visual Basic. I was excited to be able to incorporate some of the material into a recent session of the C# programming course for a client. The course covers the basics of writing multi-threaded code, but we were able to go further.

Here’s the scenario. We had data that we wanted to persist into XML files. After reading and writing the XML formatted data, we decided it would be better to both compress and encrypt the data before writing it to disk. Compression and encryption can both be rather CPU-intensive operations. Wouldn’t it be better if we could have the compression and encryption be performed in parallel, incorporating multiple CPU cores? We were able to accomplish this using the pattern on page 56 of the whitepaper. Essentially, we used a special thread-safe collection named BlockingCollection, wrapped in a Stream interface and layered between the GzipStream and CryptoStream objects, in order to perform the operations simultaneously.

The whitepaper is full of tricks like this. If you are interested in exploring this topic further, I encourage you to check it out. Students who have learned C# programming by taking one of our classes should be able to use the whitepaper to improve their code. If you are not sure you have the knowledge to take advantage of the code examples in the whitepaper, we would love to see you in our classroom!

Also, don’t forget about our 2 day course titled Delegates, Events, Lambdas and LINQ in C# (we have a Visual Basic version as well). This course will teach you a functional programming style and move you from a beginning to intermediate-level programmer. Come learn from us!