Wednesday, 13 January 2016

LINQ

LINQ (Part 1)

Definition: "LINQ(Language Integrated  Query) is a Microsoft programming methodology that adds formal query capabilities into .NET based programming languages".It offers comprehensive syntax for manipulating data .

Why LINQ:

  1. Reduce the Amount of Code.
  2. A better understanding of the intent of what the code is  doing .
  3. A similar set of LINQ queries can be applied on different data sources.
  4. LINQ enables queries as first class citizen in C# and Visual Studio.
The building Blocks of LINQ
There are two fundamental blocks in LINQ
  1. Sequence
  2. Element
A sequence is instance of class that implements IEnumerable<T> interface.A sequence is basically a list of items and each item is treated as element.
There are two types of sequences.
  1. Local
  2. Remote
  • Local Sequence implements IEnumerable <T> interface. 
  • Remote Sequence implements IQueryable<T> interface.
Example of Remote Sequence implements will be discussed later.

Example of Local Sequence:



  Out Put:





















The above example is about a local sequence .Now lets how we can manipulate it very easily with the help of LINQ.

Example:
Write a code that returns only those values which are greater than 2.
Out Put:




















You can see that how we can easily manipulate data and can get result according to our requirements.
Another important feature of LINQ is Deferred Execution.
Deferred Execution:
It means that the execution of LINQ query does not execute at the time of creation. Rather it is executed when it is used.
Actually the execution of LINQ query starts with the foreach loop.
Example:
Out Put:


















Notice that result 99 has been included even at that time the query was constructed.
There are numbers of operators that runs at the time of query creation like ToArray, ToDictionery etc.
Example:
Out Put:

















Notice that 99 is not included,because of additional ToArray().


Tuesday, 12 January 2016

                 Multi-Threading and Asynchronous                                                                    (Part 2) 

 In this blog, we will discuss about Join method , foreground thread and background thread and ParameterizedThreadStart.                              
1. Join Method
Join is synchronous method that blocks the other thread until the thread which is on the CPU terminates.
Example:
Code:

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

namespace SimpleThread
{
    class Program
    {
        //Thread Method
        public static  void ThreadMethod()
        {
            //Loop
            for (int i = 0; i <= 5; i++)
            {
                Console.WriteLine("Thread 0");
                
            }
                
        }
        public static void ThreadMethod1()
        {
            //Loop
            for (int i = 0; i <= 5; i++)
            {
                Console.WriteLine("Thread 1");

            }


        }

        static void Main(string[] args)
        {
            
            //Thread Declartion and calling 
            Thread thread = new Thread(new ThreadStart(ThreadMethod));
            thread.Start();//Start Thread
            Thread thread1 = new Thread(new ThreadStart(ThreadMethod1));  //thread for Method2
            thread1.Start();//Start Thread
            Console.ReadKey(); //For holding Screen
        }
    }

}

OutPut1:
OutPut2:
Note:Every time you compile the code,you might get the different answer.So do not worry about that.
Now lets look what happen with the use of Join method.

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

namespace SimpleThread
{
    class Program
    {
        //Thread Method
        public static  void ThreadMethod()
        {
            //Loop
            for (int i = 0; i <= 5; i++)
            {
                Console.WriteLine("Thread 0");
                
            }
                
        }
        public static void ThreadMethod1()
        {
            //Loop
            for (int i = 0; i <= 5; i++)
            {
                Console.WriteLine("Thread 1");

            }


        }

        static void Main(string[] args)
        {
            
            //Thread Declartion and calling 
            Thread thread = new Thread(new ThreadStart(ThreadMethod));
            thread.Start();//Start Thread
thread.Join();    //Join Method
            Thread thread1 = new Thread(new ThreadStart(ThreadMethod1));  //thread for Method2
            thread1.Start();//Start Thread
            Console.ReadKey(); //For holding Screen
        }
    }

}

Explanation:
The only change is  the thread.Join() method. Now the second thread would not execute until first thread terminates.
Output:

Now after every compilation you would get this result.

2.Foreground and Background  Thread
Foreground thread keeps your application alive.Once foreground thread ends ,application ends and background threads also terminates.By default ,all threads are foreground.

Note:
To make a thread background just  make the isBackground property true. If this property is false of a thread, it means it is foreground.
e.g 
Thread t=new Thread();
t.IsBackground = true;

Code:
 class Program
    {
        public static void ThreadMethod()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("Foreground Thread");
                Thread.Sleep(300);
            }
            Console.WriteLine("Foreground thread is terminated");
        }
        public static  void ThreadMethod1()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("Background thread");
                Thread.Sleep(200);
            }
        }




        static void Main(string[] args)
        {
            Thread thread = new Thread(new ThreadStart(ThreadMethod));
            thread.Start();
            thread.Join();       
            Thread thread1 = new Thread(new ThreadStart(ThreadMethod1));
            thread1.IsBackground = true;     //to make a thread background
            thread1.Start();

        }
    }
Out Put:
Foreground thread will execute ten times and application will terminated.
Explanation:
 As I have used Join method ,with which foreground thread will execute until it terminate. As second thread is background and background thread executes till the execution of foreground thread.As foreground thread terminates ,background thread also terminates .So when the above code executes,the first thread will executes ten times and then application will end.
Note:
In Console Application ,if use Console.ReadKey() for screen .The background thread will also execute ten times because Console.Readkey() behave as foreground thread.And we know that background thread executes until foreground thread is alive.

3. ParameterizedThreadStart
We can pass data through start method of a thread. For this purpose ,we use ParameterizedThreadStart delegate instead of  simple ThreadStart  delegate.

Example:
class Program
    {
        public static void ThreadMethod(object o)
        {
            for (int i = 0; i <(int)o; i++)
            {
                Console.WriteLine("thread Proc{0}", i);
            }
            
        }
        static void Main(string[] args)
        {
            Thread thread = new Thread(new ParameterizedThreadStart(ThreadMethod));
            thread.Start(5);
            Console.ReadKey();
        }
    }
OutPut:
thread proc0
thread proc1
thread proc2
thread proc3
thread proc4
Explanation:
In that case ,value is passed to threadMethod as object,You can cast it to any other type.















                      Multi-Threading and Asynchronous                                                                 (Part 1)            

The early computers were based on batch processing .In batch processing ,a central processing unit(CPU) was capable of doing one task at a time.If a CPU has to take long time to execute a task,the other processes would have paused. In that case the whole machine would freeze.The things can be more worse,if there is a bug in the running task.The only solution is to restart the machine. The solution of this problem is Thread. In modern Operating systems each application runs in its own process. If this application affects ,the other processes would remain unaffected. Each process has its own "Virtual Memory". Each process is allowed to run for a particular time period.When this time period overs,thread is paused, it's state is saved and operating system switches to another thread.It is called "Context Switching".Actually at one time ,only one process runs on CPU. But today,as computing is so much fast and powerful and context switching happens so fast that we feel that computer is executing many tasks at a time.In .NET,for threading we use Thread Class.It can be found in System.Threading name space.

Note:Always import System.Threading in your project before using Thread Class .

Example:This is a simple example of threading.Common Mistake:When you call a function in Thread class,people commonly call it parenthesis like ().Do not call it with parenthesis.Just write down the name of the method.

Output:

















The above example shows an example of using the Thread class to run a  method . The Console class synchronizes the use of the output stream for you so you can write to it from multiple threads. Synchronization is the mechanism of ensuring that two threads don’t execute a specific portion of your program at the same time. In the case of a console application, this means that no two threads can write data to the screen at the exact same time. If one thread is working with the output stream, other threads will have to wait before it’s finished.