Parallel Programming using Task and Parallel

As we all know that, now a days hardware world is booming and its processing power increases, the responsibility lies with developers to utilize such power. In order to utilize hardware resources more efficiently we should use multi-threading approach in our programming.

In the past, parallelization required low-level manipulation of threads and locks.

Sample for Thread

 //Declare and Start Thread.
 Thread th1 = new Thread(new ThreadStart(SamplePrograme));
 th1.Start();

//Method
public static void SamplePrograme()
{
        Console.WriteLine("Sample Method called using thread.");
}

Visual Studio 2010 and the .NET Framework 4 enhance support for parallel programming by providing a new runtime, new class library types, and new diagnostic tools. These features simplify parallel development so that you can write efficient and scalable parallel code in a natural idiom without having to work directly with threads or the thread pool.

You can start the thread in the same way using Task as shown in below code.

var t3 = new Task(SamplePrograme);
t3.Start();

Task Parallel Library provide various advantages over threading.

>> You can start one task and pass the result of the same to another task and execute it.

var t1 = Task.Factory.StartNew(() => { DoSomeImportantWork("WhiteX"); }).ContinueWith((previousTask) => {DoSomeOtherImportantWork("WhiteX", 1);});

var t2 = Task.Factory.StartNew(() => { DoSomeImportantWork("Mr. X"); }).ContinueWith((previousTask) => { DoSomeOtherImportantWork("Mr. X", 2); });

public static void DoSomeImportantWork(string name) {
            Thread.Sleep(1000);
            Console.WriteLine("Hi, " + name);    
}

public static void DoSomeOtherImportantWork(string name, int i) {
            for (int j = 0; j < 10; j++) {
                counter = j;
                Console.WriteLine("{0} is doing some other important work. Counter value is {1}", name, counter);
            }
}

>> Using Parallel class you can execute the multiple tasks like shown in below code

Parallel.Invoke(() => { DoSomeImportantWork("Mr. A"); }, () => { DoSomeOtherImportantWork("Mr. A", 1); }, () => { DoSomeImportantWork("Mr. B"); }, () => { DoSomeOtherImportantWork("Mr. B", 2); });

>> There are two methods using those you can hold the execution of other codes till specified thread(s) completed. Those methods are:
Task.WaitAll();
Task.WaitAny()

Note*:

What we have  discussed is just the basic to start with Task Parallel Library. You can explore more by defining and executing code with different options.

Complete code for your practice

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace TaskParallelLibrary
{
    class Program
    {
        static int counter = 0;
        static void Main(string[] args)
        {
            var t1 = Task.Factory.StartNew(() => { DoSomeImportantWork("WhiteX"); }).ContinueWith((previousTask) => {DoSomeOtherImportantWork("WhiteX", 1);});
            var t2 = Task.Factory.StartNew(() => { DoSomeImportantWork("Mr. X"); }).ContinueWith((previousTask) => { DoSomeOtherImportantWork("Mr. X", 2); });
            
            var t3 = new Task(SamplePrograme);
            t3.Start();
                        
            Task.WaitAll(t1,t2);
            
            Parallel.Invoke(() => { DoSomeImportantWork("Mr. A"); }, () => { DoSomeOtherImportantWork("Mr. A", 1); }, () => { DoSomeImportantWork("Mr. B"); }, () => { DoSomeOtherImportantWork("Mr. B", 2); });

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();

            Thread th1 = new Thread(new ThreadStart(SamplePrograme));
            th1.Start();

        }

        public static void SamplePrograme()
        {
            Console.WriteLine("Sample Method called using thread.");
        }

        public static void DoSomeImportantWork(string name) {
            Thread.Sleep(1000);
            Console.WriteLine("Hi, " + name);    
        }

        public static void DoSomeOtherImportantWork(string name, int i) {
            for (int j = 0; j < 10; j++) {
                counter = j;
                Console.WriteLine("{0} is doing some other important work. Counter value is {1}", name, counter);
            }
        }

        
    }
}
Advertisements

#parallel, #parallel-programming, #task

Optional Parameters

Let’s start with OOPs feature called function overloading.
Function overloading feature allows developer to overload the same function with different parameters or return type.
Below is the simple example of the same

 static void PrintData(string firstName, string lastName, int age)
 {
            Console.WriteLine("{0} {1} is {2} years old.", firstName, lastName, age);
 }
 static void PrintData(string firstName, string lastName)
 {
            PrintData(firstName, lastName, 0);
 }
 static void PrintData(string firstName)
 {
            PrintData(firstName, null, 0);
 }

Using above code we can call PrintData function with different no. of parameters. If you look into the declaration of functions we can say that based on how the function being call it is passing some default value if it is not being supplied while calling function to print the value i.e. static void PrintData(string firstName, string lastName, int age) function.

The same can be achieve with the help of optional parameter. Declaration is very simple, to make the parameter as optional parameter syntax is DataType ParameterName = DefaultValue

So, the declaration of the above overloaded functions using optional parameter would be

static void PrintData(string firstName, string lastName = null, int age = 0) {
       Console.WriteLine("{0} {1} is {2} years old.", firstName, lastName,age);
}

Note*: All required parameters should be first in the parameter list and all optional at the end.
If there is situation to declare them in middle, then, while passing values to optional parameters you should use named parameter way to call method with optional parameters.

PrintData(firstName: "White", age: 25);

#optional-parameter-in-c

The dynamic Keyword and Late Binding

C# is a statically typed language that means we cannot assign object of one type to another.For example

If we have created object of string like
var Data = “string”;
so, we cannot assign int value to Data object using
Data = 1;

If you try to do above conversion then compiler will through the error saying that “Cannot implicitly convert type ‘int’ to ‘string'”.
This we can resolve using the dynamic keyword.
dynamic Data = “string”;
Data = 1;

This time compiler will not through any error because dynamic “represents an object whose operations will be resolved at runtime”.

The main use of dynamic object is to create an “ExpandoObject” object.
Expando Object means you can create properties for that object as per your need and use it in your program.

For example:
Data = new ExpandoObject();
Data.Name = “WhiteX”;
Data.Type = “Learning”;
Console.WriteLine(“{0} – {1}”, Data.Name, Data.Type);

The complete code for above example is

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;

namespace Dynamic
{
    class Program
    {
        static void Main(string[] args)
        {

            dynamic Data = "string";
            Console.WriteLine(Data);
            Data = 1;
            Console.WriteLine(Data);

            Data = new ExpandoObject();
            Data.Name = "WhiteX";
            Data.Type = "Learning";
            Console.WriteLine("{0} - {1}", Data.Name, Data.Type);

        }
    }
}

Note*: Please use this dynamic keyword feature when you really need it otherwise go with static type of object because if you do any mistake it will be catch at runtime only.

#dynamic-keyword-or-late-binding

Anonymous Types

Using anonymous type you can create your own objects without defining them.

Let’s understand what does it mean. In below example we have created the collection of company and then extracted the data from it using the linq. Then we have loop through the each object and printed the value on console.

class Company
{
        public string Name { get; set; }
        public string Type { get; set; }
}

var Companies = new List{
        new Company{ Name = "WhiteX", Type ="Learning" },
        new Company {Name = "WhiteX", Type ="Solution"},
};

//Linq
Console.WriteLine("\nUsing Linq.");
var Result = from c in Companies
             select c;

foreach (var item in Result){
         Console.WriteLine("Name: {0} \t Type: {1}", item.Name, item.Type);
}
//End Linq

In the above example, what compiler will do, it will create the object of return data type of LINQ query and assign to Result variable.

In the beginning I have mentioned that “Using anonymous type you can create your own objects without defining them”. It new if you want to create your own object with different property name using the existing object that you can do in Linq query itself by using anonymous type. To create anonymous type you need to use the new keyword in select query along with curly ({}) braces and then specify the property name you want to use for newly created object.

//Anonymous Type
Console.WriteLine("\nUsing Anonymous Type.");
var AnonymousResult = from c in Companies
                      select new { CompanyName = c.Name, CompanyType = c.Type};

foreach (var item in AnonymousResult)
{
        Console.WriteLine("Name: {0} \t Type: {1}", item.CompanyName, item.CompanyType);
}    
//End

Above shown is the sample code for the anonymous type created using company object.

Below is the complete code for above example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AnonymousType
{
    class Program
    {
        static void Main(string[] args)
        {
            var Companies = new List{
                        new Company{ Name = "WhiteX", Type ="Learning" },
                        new Company {Name = "WhiteX", Type ="Solution"},
            };

            //Linq
            Console.WriteLine("\nUsing Linq.");
            var Result = from c in Companies
                         select c;

            foreach (var item in Result){
                Console.WriteLine("Name: {0} \t Type: {1}", item.Name, item.Type);
            }
            //End Linq

            
            //Anonymous Type
            Console.WriteLine("\nUsing Anonymous Type.");
            var AnonymousResult = from c in Companies
                                  select new { CompanyName = c.Name, CompanyType = c.Type};

            foreach (var item in AnonymousResult)
            {
                Console.WriteLine("Name: {0} \t Type: {1}", item.CompanyName, item.CompanyType);
            }    
            //End

        }
    }

    class Company
    {
        public string Name { get; set; }
        public string Type { get; set; }
    }
}

Note*: When you create the anonymous type all properties become read only.

#anonymous-type

Basic of Class

A class is a template, use to create an object.
A class is made up of a members which consists of fields and methods, fields are the variable which hold the state for the object and methods are the operation an object can do.
Constructor is a special type of method use to initialize the object, or use to initialize the default values for the fields.It doesn’t have a return value since it implicitly return the object.
To be accessible from another class it is defined with the public access modifier.
If constructor is not declared for the class, compiler create the default constructor for it with 0(zero) arguments at the runtime.
this: Is a special keyword use to access the current instance of a class.
We can overload the constructor for different parameters.
We can call the another constructor from one: syntaxt this(p1, p2);

#class

Conditional Statement Syntax

If…Else
.if (condition){statements}
else if(condtion){statements}(0-infinity)
else(statements}{0-1}

Switch
.switch(variable)
{
case value: statements; break; (0-infinity)
default: statements; break; (0-1)
}

Loop Statements:
Loop statements are used to execute the code block several times.

While:
while(condtion){statements}
Do-while:
do {statements} while(condition)

For:
for(initialization; condition; increment){statements}

Foreach:
foreach(variable in array){statements}

There is two special statements there in loop statements:
break: end loop
continue: start next iteration (Send code execution to the beginning of the next iteration)

 

#conditional-statements

Basic of Array

Arrays are data structure used to store collection of values.
Declaration: Datatype[] variable = new Datatype[length];
All elements should be of same data types.
We can assign value to array elements by using [] square brackets and index inside it and then assignment operator.
f. ex: arr[1] = 0;
You can also assign the value in advance using curly braces notation.
f. ex: int[] y = new int[] {1,2,3};              
          int[] y = {1,2,3};
There are also two types of multi dimention array in C# retangular and jagged array.
In declaration it contains comma for seperation of dimention and jagged array is array of arrays.
Rectangular: int[,] a = new int[1,1];
Jagged: int[][] = new int[2][];

#array