Sunday, April 20, 2014

Introduction to Parallel Programming in C# Part 1

What is Parallel Programming?

Today PCs and workstations normally have more than 2 cores which enable multiple threads to be execute simultaneously. To get advantage from this multiple cores, we can write our code to distribute the work across  multiple CPUs.To do that with .NET Framework 4.0 Microsoft introduced the new feature called parallel programming. (Apart from the Threading. Because threading was there since .NET framework 1.0).

You have to use Task Parallel Library(TPL), Parallel LINQ and many other support classed to write the application which support for the parallel programming. But in this article I'm mainly going to use the TPL, as an introduction to this topic.

How to write the Simple Task
====================

Example :






















Task class, the  most fundamental class for parallel programming. You will notice this class in each and every example in this article. Also we use Factoary.StartNew() methods only for simple task such as no input parameters and no out put result.

Create Basic Task
=================

You can use 4 different ways to create basic task in  C# parallel programming.
 1. Use Action delegate with method

Example :



 2. Use  anonymous delegate.

Example :



 3. Use lambda expression with method name

Example :



 4. Use lambda expression with anonymous method

Example :



How to use Task State
=================
You are able to give the state for a Task by passing an instance of Action<object> . Task State allow to perform similar operation on different data.

Example :
































How to getting a Result From Task
==========================

To retrieve the result from your task create a instance of Task<T> where T is type of result that will be return from the task.

Example:








































Form Part 2 I will cover another few basic topics in Parallel programming. 

Happy Coding!!!!!!!!!!!!!!!!!!!!!