Friday, January 25, 2013

Lambda Expression, Statement Lambda, Action Delegate, Func Delegate, Differences Between Action and Func and Instantiating Delegates with Lambda

Continuing from last page:
Lambda expressions or statement lamda can be passed where a delegate is expected.

Lamda expressions may or may not expect input parameters and have an expression to right of lambda that may evaluate to a return value.

      Func<int, int, int, int, int> hello = (a, b, c, d) => a + b + c + d;

   here a,b,c,d are input parameters and return type is int which is result of e
xpression (a+b+c+d). 

In above lambda expression is assigned to Func delegate which accepts 4 input parameters of type 'int' and return type is 'int' again.


We have to make sure, lambda expressions input is convertible to delegate's input type & return of lambda is convertible to delegate's return type.



In above case (a+b+c+d) will be of type of int which is same of Func<int,int,int,int,int TResult> delegate's return type i.e. int.



Lambda expression can also contain statements to right of lamda that might not return any value.


           Action<int> mm = (a) => Console.WriteLine("EEE");
      mm(5);

In above example right side of expression does not evaluate to anything though it accepts a parameter 'a'. This is assigned to default Action<int> delegate which does not expect any return type, but has an input parameter of type 'int'.


Now let us see what is a statement lambda. Statement lambda is similar to lambda expression but statement(s)/expression to the right of lambda is enclosed in {} braces.
They can contain multiple statement since they are enclosed in braces. Braces also indicate scope /block of lambda statement. 


                Action<int> actw = (a) => 
            {
                string s = "square = " + a * a;
                s = s + " - new";
                Console.WriteLine(s); 
            }

Here we are assigning statement lambda to a delegate that has single input parameter of type int. We are not returning anything from lambda but redirecting the square of number to console.


We use lambda and anonymous methods only in simple scenarios where a set of simple statements can be passed in method, instead of having dedicated method of handling or instantiating delegate.
In below example, I'm invoking a delegate and assigning a statement lambda for callback. Here having a callback method that would just print completion status would not make much sense and hence I replaced it with a lambda expression which outputs the delegate's method execution status in the callback.
Here AsyncCallback expects a method that accepts IAsyncResult parameter and return type is void. Our statement lambda accepts this IAsyncResult  as input and returns nothing and hence can be passed in as method that is expected by AsyncCallback.


        public static void ExecuteDelegate(Func<int, int, int, int, int> hello)
        {
                hello.BeginInvoke(2, 3, 4, 5,                
                   new AsyncCallback((asyncresult) => {  
                          Console.WriteLine("Completed = " +  
                                    asyncresult.IsCompleted); }),                
                                  null);
        }


Till now I have only use Func<> and Action<> delegates but lambda can be used for any delegate of matching return and input types. Func and Action are the delegates provided by default by the framework to avoid overhead of writing our own delegates for general cases. These delegates are generic they are extended to accept 0, 1, 2, 3 or more parameters. Number of input parameters that are accepted by both delegates was 0 to 4 in .NET 3.5.


Main difference between Action delegate and Func delegate is,


Action - delegate that does not have return value and accepts up-to four input parameters. (.NET 3.5)
Action also can encapsulate a method that take no input and no return value. 

Types:
Action
Action<in T1> - in represents input parameter.
Action<in T1,in T2>
Action<in T1,in T2,in T3>
Action<in T1,in T2,in T3,in T4>

Func<TResult> - Func delegate is used when we have a return value but input parameter list is optional. Func delegate can encapsulate method that returns a value and accepts no input. Func can encapsulate methods that have 0 - 4 in put parameters and return a value. Last value in parameter list represents the return type.

Func<TResult> - TResult represrents return type.
Func<in T1, out TResult> 
...............


delegate void PrintCharsDelegate(string s);


PrintCharsDelegate del = (s) =>
                   {
                       Console.WriteLine("Encryted String for {0} = ", s);
                              foreach (char ch in s)
                              {                                                   
                                                   Console.Write((char)((int)ch+1));
                              }
                   };
del("Hello");



Here statement lambda which encrypts the given string, is assigned to delegate which accepts string and returns nothing.

Anonymous methods are very similar to statement lambdas. They can be used to instantiate delegates just like statement lambda. We will see them in another article




Wednesday, January 23, 2013

Anonymous Methods, Lambda Expressions, lamda vs anonymous and their advantages

Anonymous methods:


Anonymous methods are introduced in .NET 2.0. Anonymous methods are inline methods with no name that can be directly assigned to a delegate. These methods are set of statements without any special syntax as in lambda expressions.

Advantages of anonymous methods over lambda are:

 They can be assigned/converted to delegate of any signature. They do no need parameter list to be mentioned like in lambda expressions.

Examples:

 Example 1.a

button1.Click += delegate(System.Object o, System.EventArgs e)
                   { System.Windows.Forms.MessageBox.Show("Click!"); };
Example 1.b
delegate int Square(int k);
Square d = new delegate(int k){return k*k;};

Common for Both Lambda and Anonymous methods:

  1. We avoid overhead of writing methods for handlers or delegate by using anonymous methods whenever possible. 
  2. They can't be explicitly called in code. 
  3. They can't contain goto or break or continue statements where the target is out of expression or method block.
  4.  Scope of variables in anonymous methods is method block only.
  5.  They can't accept parameters using ref or out keyword.
  6.  They can use variable declared outside their scope and such variable are called outer variables.

Lambda Expressions:


Lambda expressions are introduced in C# 3.0. They are used to instantiate a delegate by an inline method. This inline method will contain lambda (=>) after the input parameter list and statement to the right of lambda symbol. 

(input parameters) => expression

By using lambda expressions we can write local methods that can be passed as arguments that expect delegate as an argument.
    
     (x) => x? 5:0;

  () => SomeMethod() //zero parameters

Here, x is the input parameter. 

Statement lambda is similar to lambda expressions where in set of statements to the right of lambda are enclosed in {} and parameter list is to the left of lambda operator. 

      (input parameters) => {statement;}

Lambda expression can only be used to instantiate delegate of particular signature.

The general rules for lambdas are as follows:

  • The lambda must contain the same number of parameters as the delegate type.
  • Each input parameter in the lambda must be implicitly convertible to its corresponding delegate parameter.
  • The return value of the lambda (if any) must be implicitly convertible to the delegate's return type.







Sunday, January 6, 2013

Abstract Class vs Interfaces (C#) - Differences, Recommendations about when to use what?

This is a favorite question of any interviewer. Probabilities are less where interviewer expects syntactic differences rather one might be looking at design level differences. Next question which follows is "When do you prefer interface over abstract classes" or other way round. I have collected answers over the internet to compile one simple page to answer this question.

Below is from John Noah's interview questions comiplation:


An abstract class can provide complete, default
code and/or just the details that have to be
overridden.

An interface cannot provide any code at all,just
the signature.

In case of abstract class, a class may extend
only one abstract class.

A Class may implement several interfaces.

An abstract class can have non-abstract
methods.

All methods of an Interface are abstract.

An abstract class can have instance variables.
An Interface cannot have instance variables.

An abstract class can have any visibility:
public, private, protected.

An Interface visibility must be public (or)
none.

If we add a new method to an abstract class
then we have the option of providing default
implementation and therefore all the existing
code might work properly.

If we add a new method to an Interface then
we have to track down all the implementations
of the interface and define implementation for
the new method.

An abstract class can contain constructors .
An Interface cannot contain constructors .

Abstract classes are fast.

Interfaces are slow as it requires extra
indirection to find corresponding method in the
actual class.


Below answers are from MSDN.

When shall we prefer Abstract classes or Interface over other? 

  • If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.

  • If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.

  • If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.

  • If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.


Friday, December 7, 2012

WPF - CheckAccess, Invoke and BeginInvoke On Dispatcher(Similar to InvokeRequired) C#

Assuming we are aware of thread safe model of updating control's text from a different thread(not the main thread), I will explain how do we do the same in WPF.

Every control has a DispatcherObject. Just like in Windows Forms only the thread that created Dispatcher can access that object. We will use either BeginInvoke or Invoke on this dispatcher object to update the text  of the control. Invoke is synchronous and hence will block the call until main thread completes this request. Be cautious while using Invoke in multithreading applications, you might get blocked on this call and you might lose the whole point of being on different thread.

BeginInvoke is asynchronous call on the method that you specify in the delegate. Both Invoke and BeginInvoke accept delegate to the method to be invoked as argument and also parameters to this method as object array. 

For identifying whether we are trying to update control's property on main thread or some other thread we used InvokeRequired in Windows Forms, in WPF we use CheckAccess() method on the dispatcher object of control. Note intellisense might not work for this method, you can go ahead and type it.

I have copied a simple example which combines concept of AutoResetEvent and also BeginInvoke and check access which avoid any "InvalidThreadException: Calling thread can not access this object because a different thread owns it"! exception.

I have used a simple delegate:
        delegate void  textupdater(string text);

private void AutoResetEvent_Click(object sender, RoutedEventArgs e)
        {
            textBox1.Text = string.Empty;
            
            Thread t = new Thread(new ParameterizedThreadStart(HelloWordlInLoop));            
            t.Start(10);
            handle.WaitOne();
            updateText("In the main thread after event handle has been reset");
        }

        void updateText(string text)
        {
            try
            {
                if (textBox1.Dispatcher.CheckAccess())
                {
                    textBox1.Text += text;
                    textBox1.Text += "\n New Update via BeginInvoke";
                }
                else
                {
                    textBox1.Dispatcher.BeginInvoke(new textupdater(updateText), DispatcherPriority.Normal,     
                                                     new object[] { text });
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        void HelloWordlInLoop(object obj)
        {
            int i = (int)obj;
            while (i-- > 0)
            {
                Thread.Sleep(1000);
                updateText("\n Updating from Second Thread without setting EventHandle. i = " + i.ToString());
            }
            handle.Set();
        }



Friday, September 7, 2012

Difference between TRUNCATE, DELETE and DROP TABLE in SQL (Transact-Sql)


1. Both Truncate and Delete are used to delete rows from a table.

2. Truncate is like a delete command without a WHERE clause. 

3. Truncate deletes all rows of a table without logging for each row deletion. Truncate is a DDL command whereas Delete is a DML command.

4. Delete allows you to choose the rows to be deleted based on some condition but Truncate clears everything. Delete logs for each row it deletes, also will raise trigger if there is one and also it acquires lock before deleting that row.

5. Truncate removes all the rows in the table but retains its table structure, indexes, columns, constraints etc. Even Delete retains the constraints, structure, columns,etc.

6. Drop table completely removes a table from the data base including its structure, constraints etc. 

7. We cannot use Truncate on table that has Foreign Key referenced and even on a table that has participated in indexed view.

8. Truncate cannot activate Trigger whereas Delete can.

Advantage of Truncate over Delete as explained in MSDN:

Compared to the DELETE statement, TRUNCATE TABLE has the following advantages:
·         Less transaction log space is used.

The DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row. TRUNCATE TABLE removes the data by deallocating the data pages used to store the table data and records only the page deallocations in the transaction log.

·         Fewer locks are typically used.

When the DELETE statement is executed using a row lock, each row in the table is locked for deletion. TRUNCATE TABLE always locks the table and page but not each row.

·         Without exception, zero pages are left in the table.

After a DELETE statement is executed, the table can still contain empty pages. For example, empty pages in a heap cannot be deallocated without at least an exclusive (LCK_M_X) table lock. If the delete operation does not use a table lock, the table (heap) will contain many empty pages. For indexes, the delete operation can leave empty pages behind, although these pages will be deallocated quickly by a background cleanup process.

Examples:

TRUNCATE TABLE Employee;
DELETE FROM Employee Where Salary> 10000;
DROP TABLE Employee;





Wednesday, August 22, 2012

Performing Inner Join and Left Outer Join in LINQ Queries

Linq supports joining just like any other querying language. Syntax is bit different from standard SQL query though. Also We need to add some logic to achieve Left Outer Join as there is no standard keyword for this.

In our example, we have list of people with their name and their address. We also have list of houses in city with their house name and owner name. 

a. Lets understand performing inner join. Inner join joins two tables based on some condition. Results will include only those entries from joined tables which match the condition. To illustrate inner join we need to find out all the people who own a house with their address. We use "join" keyword with "on" clause to achieve this inner join.  Example I have provided is self explanatory.

b. If we have to output all the people along with their house names if they own otherwise print empty string, then we can go for left outer join. In this join lets make People as left item. We use  DefaultIfEmpty() method to ensure for every People entry will appear in output result. DefaultIfEmpty() provides empty\default for each non matching sequence i.e for any People object if matching sequence in Houses is empty then DefaultIfEmpty returns single default item. In next select we can check if result is default or contains some value. If result sequence contains some value other than default, then we can output that value otherwise we can output empty string or default value.

Below example shows how Left Outer Join and Inner Joins are performed in our example:



        public static void Main(string[] args)
        {
            People p1 = new People { Name = "Manu", Address = "Marathalli" };
            People p2 = new People { Name = "Dada", Address = "BTM" };
            People p3 = new People { Name = "Saavu", Address = "Kunadanahalli" };
            People p4 = new People { Name = "Vasanth", Address = "Munnekolala" };
            People p5 = new People { Name = "Andy", Address = "Jayanagar" };
            People p6 = new People { Name = "Putta", Address = "JP Nagar" };

            Houses h1 = new Houses { HouseName = "Jaipur Palace", HouseOwnerName = "Putta" };
            Houses h2 = new Houses { HouseName = "Mysore Palace", HouseOwnerName = "Manu" };
            Houses h3 = new Houses { HouseName = "Pune Vihar", HouseOwnerName = "Vasanth" };

            List<People> people= new List<People> { p1, p2, p3, p4, p5, p6 };
            List<Houses> houses = new List<Houses> { h1, h2, h3 };

            Console.WriteLine("Inner Join Results:");
           //Inner join to print all the Person with house with house name
            var houseOwners = from p in people
                              join h in houses on p.Name equals h.HouseOwnerName
                              select new { p.Name, PersonHouseName = h.HouseName, p.Address };

            foreach (var h in houseOwners)
            {
                Console.WriteLine(h.Name+" : "+h.PersonHouseName+" : "+h.Address);
            }

            Console.WriteLine("************************************************************************");

           //Left outer join to print all the people and also their house names if they have one otherwise empty string
            Console.WriteLine("Left Outer Join Results:");
            var allppl = from p in people
                   join h in houses on p.Name equals h.HouseOwnerName into tempOwners
                   from nonOwners in tempOwners.DefaultIfEmpty()
                   select new { p.Name, PersonHouseName = (nonOwners==null)? string.Empty:nonOwners.HouseName, p.Address };

            foreach (var h in allppl)
            {
                Console.WriteLine(h.Name + " : " + h.PersonHouseName + " : " + h.Address);
            }
        }

    public class People
    {
        public string Name {set;get;}
        public string Address { set; get; }
    }

    public class Houses
    {
        public string HouseName { set; get; }
        public string HouseOwnerName { set; get; }
    }


Console Output Window:


Thursday, August 16, 2012

Threads, Threads Overhead ,Kernel Internals, Kernel Architecture and Asynchronous Methods in C# - Part 2

Thread Context Switching:


A single CPU can only do one thing at a time. Windows keeps switching between processes to give user robust & responsive system and also better overall experience. Windows Scheduler give slices of CPU time to each thread. It is called Quantum(Time period varies from architecture to architecture). After each time-slice elapses windows scheduler switches to another thread. This is called thread context switching. This switching enables multiple threads to share same CPU & hardware resources to provide "multitasking" support. 

The next thread that gets CPU might be from different process itself. In such case windows has to change to that process virtual address space as seen by the CPU before executing any code of that process or processing any data  of that process. 

Each Context switch  has to go through below steps:
  1. Save the context of the thread that just finished executing.
  2. Place the thread that just finished executing at the end of the queue for its priority.
  3. Find the highest priority queue that contains ready threads.
  4. Remove the thread at the head of the queue, load its context, and execute it.
Saving the context requires thread context must be stored somehow so that when next switch happens to that thread we can restore this information. This step of storing and restoring from thread's context structure includes,
  • Saving the values of CPU registers that were assigned to the current thread into thread's context structure inside thread's kernel object data structure.  
  • Changing virtual address space if required as explained before.
  • Loading from next thread's context into CPU registers.
This is performance overhead at the cost of giving user a responsive system. This switching would allow,
  • Avoiding CPU starvation by preempting ready threads over threads that are waiting for input or resource.
  • Execution Ready threads to be taken up according to their Priority.
  • CPU time to all the processes allowing each one to run.
  • Keep system responsive even when few threads\processes go into deadlock or infinite loop.
Hence multiple thread approach will add to number of context switches which in turn affects performance.  

Now lets see how new thread creation adds to Windows performance overhead:

When windows context switches CPU from one thread to another, previously executing thread's data and code reside in CPU cache, so that CPU does not have access RAM. This is to avoid latency in accessing information from memory. When a new thread is created, it might have to access different data and execute different code altogether. Since this will not be on CPU cache, it has to populate this data from RAM into cache, to speed up the processing speed. This might happen every time a new thread is added, thus causing performance overhead.[CLR Via C#].

Now that we understand why thread creation, destruction and maintenance causes affects performance and memory efficiency , we will see how number of threads affect GC performance.

Number of threads also affect the performance of Garbage Collector. Before collection or GC cycle, GC must suspend all the threads. GC walks through stack of each thread to mark the root of each heap object, walk their stack again to update the stack to updating the roots of objects that have moved during compaction. GC resumes all the threads only after this collection cycle. This causes GC to perform slow.

Multiple threads keep the application responsive but they also have above explained overheads. When designing an application with multiple threads we need to understand real intent of each thread and its necessity before creating one.

I will end thread overhead concepts here. In my next articles, I will go briefly into Kernel and its architecture.