Showing posts with label C# Basics. Show all posts
Showing posts with label C# Basics. Show all posts

Monday, July 8, 2013

Difference between Multi Threading and Parallel Programming

In this article we can see the difference between Multi threading and parallel programming

Why Dotnet Framework introduces Parallel Programming Even though Multi threading already exists in Framework

There is a major big difference is exists between the two concepts , but both are doing the multi task in concurrent way. Parallel programming is acts as higher layer of Threading.

Multi Threading

First Let we see about Multi Threading, Concepts,


From the above program we can invoke a 10 threads concurrently While execute the  multi threading ,I monitor the CPU Performance. My computer have 4 core processcor

CPU LOAD


Threads are executed in single core more , so load given to the core is not split based on balance. It is allocated based on the sequence , threads are allocated more to perform in single core , after the core is heavy load. remaining threads are then in remaining core.

Allocation of thread execution in core has to be handled manually by developers and it is more complex to find which core is heavy loaded , and  which core we have to execute the thread.

OutPut :

From the ouput you can see the time taken to finish each thread , along with thread id.



parallel Programming

Now Let we see parallel Programming and there advancements.
class Program
    {
        public static void Main(string[] args)
        {
            Action Measure= (body)=>
            {
                DateTime start=DateTime.Now;
                body();
                Console.WriteLine("{0} {1}",DateTime.Now-start,Thread.CurrentThread.ManagedThreadId);
            };
           
            Action Cal=()=>{for(int i=0;i<500000;i++);};
            ThreadPool.SetMinThreads(10,10);
           
            Parallel.For(0,10,_=>{Measure(Cal);});
                                   
            Console.WriteLine("Press any key.....");
            Console.Read();
        }
       
    }


From the above code , we are creating the threads in parallel. 10 threads are running at the same time in all the core , CPU load is balanced by allocating the threads equally in all core. So Allocating the Execution of threads to the Core is handled internally by parallel programming . Parallel.For(); is one of the code which is used to execute the method in parallel.

CPU LOAD 


From the above screenshot , we can find the parallel program or task library will allocate the threads in balanced manner to the core processors of system. Each Core of computer is equally loaded.

OUTPUT: 


From the Given output we can find that parallel programming is very fast then multi threading.

Let we see another program in parallel which uses task factory class ,Allocation of thread execution in core is managed by parallel programming internally.

  public static void Main(string[] args)
        {
            Action Measure= (body)=>
            {
                DateTime start=DateTime.Now;
                body();
                Console.WriteLine("{0} {1}",DateTime.Now-start,Thread.CurrentThread.ManagedThreadId);
            };
           
            Action Cal=()=>{for(int i=0;i<500000;i++);};
            ThreadPool.SetMinThreads(10,10);
           
            Measure(()=>
                   {                                           
                        Measure(()=>
                                {
                                    var tasks = new []{
                                                        Task.Factory.StartNew(()=>Measure(Cal)),
                                                        Task.Factory.StartNew(()=>Measure(Cal))
                                                        };
                                    Task.WaitAll(tasks);
                                });
                    });
           
                                   
            Console.WriteLine("Press any key.....");
            Console.Read();
        }
       
    }


 From this article , we can understand about the basic info of  parallel programming or task library and Multi threading. Difference between Parallel programming and muilt threading is also explained clearly

Saturday, July 6, 2013

Multi Threading in C#

Multi threading is managed internally by a thread scheduler, a function the CLR typically delegates to the operating system. A thread scheduler ensures all active threads are allocated appropriate execution time, and that threads that are waiting or blocked (for instance, on an exclusive lock or on user input) do not consume CPU time. 

On a single-processor computer, a thread scheduler performs time slicingrapidly switching execution between each of the active threads. Under Windows, a time-slice is typically in the tens-of milliseconds region—much larger than the CPU overhead in actually switching context between one thread and another (which is typically in the few-microseconds region). 

On a multi-processor computer, multithreading is implemented with a mixture of time-slicing and genuine concurrency, where different threads run code simultaneously on different CPUs. It’s almost certain there will still be some time-slicing, because of the operating system’s need to service


A multithreaded application allows you to run several threads, each thread running in its own process.  So theoretically you can run step 1 in one thread and at the same time run step 2 in another thread.  At the same time you could run step 3 in its own thread, and even step 4 in its own thread.  Hence step 1, step 2, step 3, and step 4 would run concurrently.  Theoretically, if all four steps took about the same time, you could finish your program in a quarter of the time

Let we see a Real time example : 

There are four persons staying in a same house, They thought they have to go outing so they decide to do there work and finish in parallel.



In this example 3,4,5,6 are the persons name (i.e Thread Id) . Start there work at the same time in parallel and finished Start time : "09:59:54.46293557

Each person have the Two work to finish. each of them to wait for all to finish there task then all of them went outing .


    class Program
    {
        static void Main(string[] args)
        {
            int persons 4;
             ManualResetEvent resetEvent = new ManualResetEvent(false);
            int toProcess = persons;
              
            for (int i = 0; i < persons; i++)
            {
                new Thread(delegate()
                {                  
                        Console.WriteLine("\nTime{1},Person :{0}",
                                   Thread.CurrentThread.ManagedThreadId,DateTime.Now.TimeOfDay);
                        Console.WriteLine();
                       for(int a=0;a<2;a++)
                        Console.WriteLine(" Person {0} : Work {1} Processed",
                                  Thread.CurrentThread.ManagedThreadId,a+1);
                 
                    // If we're the last thread, signal
                    if (Interlocked.Decrement(ref toProcess) == 0)
                        resetEvent.Set();
                  
                }).Start();
            }
  
            // Wait for workers.
            resetEvent.WaitOne();
            Console.WriteLine();
            Console.WriteLine("All person Finished there work.");
            Console.Read();
        }
 
    }

In the Above example Interlocked.Decrement(ref toProcess) == 0 will decrement the variable for each person finish there work,this will decrement the variable value by one , this is shared variable . so at the last person finished his work toProcess  variable value become Zero .

When all thread are started resetEvent.WaitOne(); will wait for all thread to finish 

This will clearly explain about the multi threading .



Threading in C#

A C# client program (Console, WPF, or Windows Forms) starts in a single thread created automatically by the CLR and operating system (the “main” thread)


All examples assume the following namespaces are imported: 

using System; 
using System.Threading; 

class ThreadTest
{
     static void Main()
     {
 
         Thread t = new Thread (Write);        //  a new thread 
         t.Start();                                           //   running Write() 

         // Simultaneously, do something on the main thread.       
         for (int i = 0; i < 1000; i++)
             Console.Write ("x");

     }
     static void Write()
     {
         for (int i = 0; i < 1000; i++) Console.Write ("y");
     }
}

Output : 
xxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyy
yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
yyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


Properties of a Thread

  • Thread.CurrentThread -> Static method gives the reference of the thread object which is executing the current code.
  • Name           -> Read/Write Property used to get and set the name of a thread
  • ThreadState -> Property used to check the state of a thread.
  • Priority        -> Property used to check for the priority level of a thread.
  • IsAlive         -> Returns a Boolean value stating whether the thread is alive or not.
  • IsBackground -> Returns a Boolean value stating the running in background or foreground.

PriorityLevels of Thread

  • Highest
  • AboveNormal
  • Normal
  • BelowNormal
  • Lowest

Difference between Var and Dynamic keyword

In this article i am going to Discuss about difference between var and dynamic keyword

Var Keyword 
 
   












1.     It is introduced in C# 3.0 version
2.     The variable type is decided at compile time itself by compiler. when we mouse over the variable it will tell the data type.
3.     Variable should initialize at the declaration itself.
               var number 10 is correct.   
               var number;     not correct error ; 
           Implicitly-typed local variables must be initialized (CS0818) 
      4.  var can't be used as type in method parameter
5.     This  is statically typed.
6.     Errors caught at compile time.
7.     We can’t reassign the value of variable to another data type, because compiler already knows what kind of data type is declared.
  var  obj=1; 
  var  obj=”name”;   Error because already it defined as int type by compiler. 


Dynamic Keyword




      1.      It is introduced in C# 4.0
      2.      This is dynamically typed. Decides the type of variable at runtime by compiler.
      3.      No needs of initialize at declare time.
e.g., dynamic str; 
§  str =”I am a string”;  //Works fine and compiles
§  str=2;                  //Works fine and compiles
       4.      Error caught at runtime.
       5.      No intellisense.
       6.   dynamic should be used as a type in method parameter
               public void dyn(dynamic dd)
        {
            dynamic add;
            add="sample";
            add=3;
        }






Implicit and Explicit Conversion in C#

In C# Language , There is concept called Type Conversions, Which will convert one type to another.

In that there are two types of Conversions
1. Implicit Conversion
2. Explicit Conversion

Implicit Conversion : 
Conversion between types can be achieved automatically is known as Implicit
 For Ex :  

        byte value1 = 10;
        byte value2 = 23;
        long  total    = value1 + value2;

Here in this example, we don't need to specify data type for the target type, internally it will convert that is implicit. value1 , value2 are byte when adding we assign the value to a variable total which is long data type.
Internally it converts the result value into long data type.

Explicit Conversion :
Conversion between types can be done Manually instead of automatically
For Ex:
        
        long val = 3000;
        int a = (int) val;       /*  valid cast . The Maximum int is 2147483647  */

In this above example, we can see that val is long data type now it is assign to int type with explicitly specify 
to which data type we have to convert . If we misses this explicit convert C# Compiler throws error.

Let we see in coding How it is works like this Implicit and Explicit conversion 

Here we take three class  Rupees Dollar  ,Euro     

Rupees can be convert to Euro or Dollar   Implicit
Dollar   can be convert to Rupees Implicit and Euro as Explicit
Euro     can be convert to Rupees or Dollar   Implicit

From the below code 20 is pass as a parameter to rupees, then it is implicitly converted to Dollar and 
Euro

/***********************************************************************/

     Rupees rup  =  new Rupees(20);
     Dollar   rdrl  =  rup;
     Euro     reur  =  rup;

   class Rupees    {
        public decimal Value{set;get;}
    
    
        public Rupees(decimal value)
        {
            this.Value = value;
        }
    
       /* Rupees can be implicitly converted to Euro */
        public static implicit operator Euro(Rupees cur)
        {        
            return new Euro(cur.Value/100 );
        }
         
        /* Rupees can be implicitly converted to Dollar */
        public static implicit operator Dollar(Rupees cur)
        {
            return new Dollar(cur.Value/50);
        }
    }
/***********************************************************************/


/***********************************************************************/
Here Dollar is convert to Euro Explicitly 

     Dollar    dlr    =  new Dollar(4);
     Euro      deur =  (Euro)dlr;
     Rupees drup =  dlr;

class Dollar
    {
        public decimal Value{set;get;}
    
    
        public Dollar(decimal value)
        {
            this.Value = value;
        }
    
        /* Dollar can be implicitly converted to Rupees */
        public static implicit operator Rupees(Dollar cur)
        {        
            return new Rupees(cur.Value*50);
        }
            
        /* Dollar can be implicitly converted to Euro */
        public static explicit operator Euro(Dollar cur)
        {
            return new Euro(cur.Value/2);
        }
    }
 /***********************************************************************/   

/***********************************************************************/
In the below code Euro is implicitly convert to rupees and Explicitly to Dollar

     Euro      eur   =   new Euro(2);
     Rupees erup =   eur;
     Dollar   edlr  =   (Dollar)eur;

class Euro
    {
        public decimal Value{set;get;}
    
        public Euro(decimal value)
        {
            this.Value = value;
        }
    
        /* Euro can be implicitly converted to Rupees */
        public static implicit operator Rupees(Euro cur)
        {        
            return new Rupees(cur.Value*100);
        }

      /* Euro can be implicitly converted to Dollar */
        public static implicit operator Dollar(Euro cur)
        {
            return new Dollar(cur.Value*2);
        }
    }
 /***********************************************************************/
public static void Main(string[] args)
{
            Rupees r     = new Rupees(20);
            Dollar   rdrl = r;
            Euro     reur = r;
            Console.WriteLine("Rupees = {0} \tDollar = {1} \tEuro = {2}",r.Value,rdrl.Value,reur.Value);
        
            Dollar  dlr    =   new Dollar(4);
            Euro    deur  =   (Euro)dlr;
            Rupees drup=   dlr;
            Console.WriteLine("Dollar = {0} \tEuro = {1} \tRupees = {2}",dlr.Value,deur.Value,drup.Value);
        
            Euro      eur   = new Euro(2);
            Rupees erup = eur;
            Dollar    edlr = (Dollar )eur;
            Console.WriteLine("Euro = {0} \tRupees = {1} \tDollar = {2}",eur.Value,erup.Value,edlr.Value);
        
            Console.WriteLine();
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
  }

Following is the ouput :                 





The full source code for Type Conversion  Code.

namespace TypeConversion
{
    class Dollar
    {
        public decimal Value{set;get;}
    
    
        public Dollar(decimal value)
        {
            this.Value = value;
        }
    
    
        public static implicit operator Rupees(Dollar cur)
        {        
            return new Rupees(cur.Value*50);
        }
        
        public static explicit operator Euro(Dollar cur)
        {
            return new Euro(cur.Value/2);
        }
    }

    class Euro
    {
        public decimal Value{set;get;}
    
        public Euro(decimal value)
        {
            this.Value = value;
        }
    
        public static implicit operator Rupees(Euro cur)
        {        
            return new Rupees(cur.Value*100);
        }
        
        public static implicit operator Dollar(Euro cur)
        {
            return new Dollar(cur.Value*2);
        }
    }

    class Rupees
    {
        public decimal Value{set;get;}
    
    
        public Rupees(decimal value)
        {
            this.Value = value;
        }
    
        public static implicit operator Euro(Rupees cur)
        {        
            return new Euro(cur.Value/100 );
        }
        
        public static implicit operator Dollar(Rupees cur)
        {
            return new Dollar(cur.Value/50);
        }
    }

    class Program
    {
        public static void Main(string[] args)
        {
            Rupees r=new Rupees(20);
            Dollar rdrl=r;
            Euro reur=r;
            Console.WriteLine("Rupees = {0} \tDollar = {1} \tEuro = {2}",r.Value,rdrl.Value,reur.Value);
            
            Dollar dlr =new Dollar(4);
            Euro deur=(Euro)dlr;
            Rupees drup=dlr;
            Console.WriteLine("Dollar = {0} \tEuro = {1} \tRupees = {2}",dlr.Value,deur.Value,drup.Value);
            
            Euro eur=new Euro(2);
            Rupees erup=eur;
            Dollar edlr=(Dollar)eur;
            Console.WriteLine("Euro = {0} \tRupees = {1} \tDollar = {2}",eur.Value,erup.Value,edlr.Value);
            
             Console.WriteLine();
             Console.Write("Press any key to continue . . . ");
             Console.ReadKey(true);
        }
    }
}


This article will make a Clear understanding of Implicit and Explicit type conversion.