Monday, December 31, 2012

Async – Await



A new asynchronous programming model introduced in C# 5.0. The programming style using (Async Await) would be as similar as like synchronous programming with slight code changes.
There are other asynchronous programming methods before such as like
1)      APM (Asynchronous Programming Model) – Begin Invoke, End Invoke…
2)      EAP (Event Asynchronous Pattern) – Event is raised after the completion of Asynchronous function.
3)      TAP (Task Asynchronous Pattern) – Using Task library that helps to build a wrapper (task) on the actual function. The status of the task can be fetched from the task object.

The next model is using Async – Await introduced in C# 5.0.
Below is a sample code, with traditional synchronous and latest asynchronous methods,
Synchronous
Function which would take some time (5 seconds) and returns a number.
  private Int32 GetNumber()
        {
            Thread.Sleep(5000);
            return 10;
        }
Asynchronous using Async Await.


        private async Task<Int32> GetNumber()
        {
            //statements are executed in synchronous manner, as long as there is
            //no await statement
            int a = 10;

            //when there is an await statment, which means compiler will understand that
            //it has to wait for the result, but since the method is marked as async hence it returns the
            //control to the calling method without blocking
            return await Task.Run(() =>
                 {
                     Thread.Sleep(5000);
                     return 10;
                 });

            //when the above task is completed, it would run  the next statements again in synchronous manner as long
            //as there is no await statement.
            a = 20;
        }

Caller :
  private async void button1_Click(object sender, EventArgs e)
        {
            Int32 result = await GetNumber();
 }

The similar async – await can be used for the delegate methods which are invoked by the task library.
Below is an example, declaring async delegate methods in a task.

Task<Int32> result1 =  Task.Run(async () =>
                    {
                        await Task.Delay(5000);
                        return 10;
             });

Note :
1)      To enable async- await – asynchronous behavior, the method should be declared as async.
2)      Method declared as async, may or may not have a await statement.
3)      If there is no await statement in a sync method, compiler executes like a synchronous method.
4)      To have a await statement, method should be declared as async .
5)      A async method always returns Task or Task<T> or can be void.

Why should a async method return type always have to be Task or Task<T> or void.

When a async method is invoked, compiler would expect that there could be a piece of code which needs to be asynchronous.
Hence when there is a await statement which might be in the middle of the code block with in the method, compiler will execute from there as a separate till the end of the code block.

Creating a task for this is because, since it has to run asynchronously it will goto the caller when an await statement is identified.
So to monitor the code execution from await statement, the return task handle would help to do.
If it is not required to bother about the further execution which would happen hence not required to handle return type and hence can be void.

Thursday, September 13, 2012

IQueryable and IEnumerable

IEnumerable helps to iterate in the collection or list objects as well known.

IQueryable is an interface and also has extension methods one among which is "AsEnumerable".
"AsEnumerable" method returns IEnumerable object.

IQueryable holds expression and return element type beside IEnumerable.

While calling "AsEnumerable" extension method, the expression is evaluated and the result can be enumerable.

So while calling extension methods after "AsEnumerable", they work on the final collection or list (In Memory).

Where as while calling extension methods of "IQueryable", they work on ahead before getting the list.
This could be the case while working on remote data object or database, it would help to apply where or order by clauses ahead on the data using extension methods before getting in memory list (IEnumerable).






Friday, July 20, 2012

Producer-Consumer Problem using TPL and Blocking Collection

.NET 4.0 frameworks, has introduced TPL (Task Parallel Library) that has several advantages in achieving concurrency. Also there are thread safe collections like “ConcurrentQueue”, “BlockingCollection”, “ConcurrentDictionary”, “ConcurrentBag”, etc….

Producer would broadcast the data maybe which should be thread safe, in case if there are multiple producers who post the data.
Consumer reads the data published may be via queue.
At a point of time consumers should know or signaled saying the posting of data is completed by the producers or source.
Below example is considering there are 3 producers (3 tasks) adding numbers from 1 to 100 to queue in parallel.
At the same time, there are 2 consumers (2 tasks) reading numbers from the queue.
So adding and reading happens parallel using 5 tasks (3 for adding, 2 for reading). However when adding is completed, reading tasks should be signaled and that helps consumers to quit from reading data.
For this we use “BlockingCollection”, which is a new thread safe collection class in .NET 4.0.
Enumerator from BlockingCollection, has a feature to pop the item from the collection. Which mean, when we iterate using enumerator of blocking collection, it not only reads the item but also removes the item which is read from the collection. Also it tries to pop the items until it is signaled (calling “CompleteAdding” method).
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
  var queue = new BlockingCollection<int>();
                var producers = Enumerable.Range(1, 3)
                    .Select(_ => Task.Factory.StartNew(
                        () =>
                        {
                            Enumerable.Range(1, 100)
                                .ToList()
                                .ForEach((i) =>
                            {
                                queue.Add(i);
                                Thread.Sleep(100);
                            });
                        }
                        ))
                        .ToArray();

                var consumers = Enumerable.Range(1, 2)
                    .Select(_ => Task.Factory.StartNew(
                        () =>
                        {
                            foreach (var item in queue.GetConsumingEnumerable())
                            {
                                Console.WriteLine(item);
                            }
                        }
                        ))
                      .ToArray();
                Task.WaitAll(producers);
                queue.CompleteAdding();
                Task.WaitAll(consumers);
 Console.WriteLine("Done!");
            }
            catch (Exception exp)
            {
                Console.WriteLine("Error : " + exp.Message);
            }
            Console.Read();




Monday, June 18, 2012

Using Tasks in APM


The “FromAsync” method in the Task Framework helps to build Task object from the “Async” methods (APM). Below code is an example of the same.

Also beside, using  “FromAsync” method, “TaskCompletionSource” object helps to set the result in the callback method.
Below code has both as examples.
namespace ConsoleApplication5
{
    class Program
    {
        delegate int delSum(int a, int b);
        static void Main(string[] args)
        {
            try
            {
                delSum oSum = new delSum((a1, a2) =>
                {
                    Thread.Sleep(2000);
                    return a1 + a2;
                });

                //Using "From Async" method to convert APM to TAP
                Task<int> aa = Task<int>.Factory.FromAsync(
                    oSum.BeginInvoke, oSum.EndInvoke, 4, 5, null);
                aa.ContinueWith(t => Console.WriteLine("using from async method " + t.Result));

                //Using "Task Completion Source", to set the task result from IAsyncResult
                TaskCompletionSource<int> source = new TaskCompletionSource<int>();
                oSum.BeginInvoke(8, 9, ar =>
                     {
                         try
                         {
                             source.SetResult(oSum.EndInvoke(ar));
                         }
                         catch (Exception exp)
                         {
                             Console.WriteLine("Error : " + exp.Message);
                         }
                     }, null);

                source.Task.ContinueWith(t => Console.WriteLine("using task completion source " + t.Result));
            }
            catch (Exception exp)
            {
                Console.WriteLine("Error : " + exp.Message);
            }
            Console.Read();
        }

    }
}



Monday, April 9, 2012

Optional and Named Parameters – C#


Visual studio 2010 C#, has extended the capability of calling a function with its argument based on name and also can omit the optional parameters which are set with default value in the function declaration.
Below example demonstrates the same.
Program.cs
  class Program
    {
        static void Main(string[] args)
        {
            try
            {
                //calling the function normally
                Console.WriteLine(CaculateArea(10, 20, "Rectangle 1"));

                //calling the function providing only "length" as named parameter and others will be default
                //which are optional
                Console.WriteLine(CaculateArea(length: 100));

                //calling the function sending all the arguments as named parameters whose order need
                //not be same as arguments order in the calling function.
                Console.WriteLine(CaculateArea(name: "Rectangle 2", width: 100, length: 200));
            }
            catch (Exception exp)
            {
                Console.WriteLine("Error : " + exp.Message);
            }
            Console.Read();
        }

        //function which width and name with default values which are like optional parameters.
        //optional parameters should always be declared at the end after the actual parametes.
        static string CaculateArea(int length, int width = default(int), string name = "No Name")
        {
            return string.Format("The area of \"{0}\" is {1}", name, length * width);
        }
    }

Output:



Partial Class and Method


Declaring a class as “partial” enables the developer to extend the capabilities of class to add extra members with in by creating the same partial class in an another file.

Ex:-
I can create below class in “Class1.cs”
  public partial class Class1
    {
        public void Method1()
        {
            Console.WriteLine("Hello this is method1");
        }
    }
I can also create a class with same name (Class1) as below, in “Class2.cs”, which means I am trying to add functions to an existing partial class.
  public partial class Class1
    {
        public void Method2()
        {
            Console.WriteLine("Hello this is method2");
        }
    }
Similarly, partial methods can be declared in a partial class and can be implemented in the specific partial class. Below example demonstrates the same.

Program.cs
    public partial class MyClass1
    {
        public void Met1()
        {
            Console.WriteLine("Method 1");
            Met2();
        }
         partial void Met2();
    }

MyClass.cs

  public partial class MyClass1
    {
        partial void Met2()
        {
            Console.WriteLine("Method 2");
        }
    }

Now when I create instance for “MyClass1” and invoke “Met1”, “Met1” when calls “Met2” it calls the implemented function in specific partial class.
Note: Partial methods cannot be declared with access specifiers and also cannot be invoked from the object of the class directly which in turn can be called in an another function(s).



Friday, April 6, 2012

Using Linq, Lamda and Indexers – Example


Below example is to create a “BookStall” (Collection of books), finding books based on “BookName” or “Price” or “Author Name and Price”.
Created “Indexer” for “BookStall” class which exposes 3 properties that returns the list of books based on “BookName” or “Price” or “Author Name and Price”.
Created a delegate (delWhereClause) in “BookStall” which returns “bool” and accepts “Book”object.
So the three indexers which are meant for different filters in book collection will create lamda expression or delegate object of type (delWhereClause) and send the delegate to a generic method “GetBooks” which applies Linq for the collection and in case of “where” it invokes the delegate which is sent as argument.

Program.cs (Console Application) :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Book objBook = null;
                BookStall objBookStall = new BookStall();
                Random objRand = new Random();

                //creating 50 books and adding to book stall
                //setting random price for each book
                for (int i = 0; i < 50; i++)
                    objBookStall.Add(new Book() { Name = "B" + i, Author = "A" + i, Price = (objRand.Next(100, 120)) });

                //Considering a book, whose name is 'B4'
                objBook = objBookStall["B4"].First();

                //Getting book based on Author and Price
                objBook = objBookStall[objBook.Author, objBook.Price].First();

                //Printing the details of "B4"
                Console.WriteLine("Book Details \n " + objBook);

                Console.WriteLine(Environment.NewLine + "Books with same Price : " + objBook.Price + Environment.NewLine);

                //Getting the books which are with similar price in the book stall and printing to Console
                objBookStall[objBook.Price].ForEach((b) =>
                   Console.WriteLine("Book Details \n " + b));

            }
            catch (Exception exp)
            {
                Console.WriteLine("Error : " + exp.Message);
            }
            Console.Read();
        }
    }

    //The book class which has the attributes related to a book
    public class Book
    {
        public string Name;
        public int Price;
        public string Author;
        public override string ToString()
        {
            return ("Book Name : " + this.Name + ", Price : " + Price + ", Author : " + Author);
        }
    }

    //Bookstall class - List of Books
    public class BookStall : List<Book>
    {
        public delegate bool delWhereClause(Book argBook);

        //Getting books based on Book Name
        public List<Book> this[string BookName]
        {
            get
            {
                return GetBooks(
                    (b) =>
                    {
                        return (b.Name.Trim().ToLower() == BookName.Trim().ToLower());
                    }
                    );
            }
        }

        //Getting books based on Price
        public List<Book> this[int Price]
        {
            get
            {
                return GetBooks(
                    new delWhereClause((b) =>
                        {
                            return (b.Price == Price);
                        }
                        ));


            }
        }

        //Getting books based on Author
        public List<Book> this[string AuthorName, int Price]
        {
            get
            {
                return GetBooks(b => b.Author.Trim().ToLower() == AuthorName.Trim().ToLower() && b.Price == Price);
            }
        }

        //Getting list of books which, invoke the where claus delegate while itterating through each book
        //in the current collection
        private List<Book> GetBooks(delWhereClause argWhereClause)
        {
            return (from b in this where argWhereClause(b) select b).ToList();
        }
    }
}

Output: