C# 4

programming, software development, devops, java, agile, web, iot, database, mobile, big data, cloud

C# 4.0 – Beginners look into parallel programming

Join the DZone community and get the full member experience.

This gives us access to what we need for parallel work. Noe, for this introduction we’re going to count the number of files in a given directory, including the subdirectories in said directory. We’re going to store all the directories in a Stack<string> just for simplicity sake. For those who have never used the Stack this is a LIFO (last-in-first-out) collection, in this case of type string.

Parallel.ForEach(TSource, TLocal) Method (Partitioner(TSource), ParallelOptions, Func(TLocal), Func(TSource, ParallelLoopState, TLocal, TLocal), Action(TLocal))

During the parallel loop we will also use Interlock.Exchange that way we can keep the proper counter variable across multiple threads (atomic method). So here is how the method looks

To test our method we will do this in our main method. Here we will pass it the directory we wish to search and our Action. In this case our action will be adding the file names to our Generic list. We will prompt for the directory and get the files and count them. which looks like this

Notice we pass the method an Action, a delegate than encapsulates a method with no parameters. We go this route so we dont have to explicitly declare a delegate. So from this beginners look you can see that parallel programming is a powerful tool offered from Microsoft, and can finally allow us as programmers to keep up (somewhat anyways) with the ever changing hardware world and performance they’re offering.

So this is a beginners look at the new parallel programming ability in C# 4.0. Next we will take a more intermediate look at parallel programming and how it can increase performance in your applications.

Like This Article? Read More From DZone

Free DZone Refcard

Getting Started With Memcached

Opinions expressed by DZone contributors are their own.

Leave a Reply

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