Friday, December 12, 2014

Async and Await usage

The goal of this post is to explain the usage of async and await keywords, how could be used to convert the existing synchronous method to asynchronous method.

Pre-Requisites:
Working knowledge of Task
Details of what async and await mean can be found in MSDN.

Asynchrony is essential for activities that are potentially blocking, such as when your application accesses the web(or writing big stream to file). Access to a web resource sometimes is slow or delayed. If such an activity is blocked within a synchronous process, the entire application must wait. In an asynchronous process, the application can continue with other work that doesn't depend on the web resource until the potentially blocking task finishes. In this scenario, the usage of wait and async keywords helps to achieve Asynchrony.

Eg: Download the RSS feed from the web asynchronously.
Implementation of this example helps to differentiate the ease of code to achieve Asynchrony with/without async and await keywords.

This could be achieved in 3 ways

Synchronous - UI will be unresponsive until there is no response from the feed server. In the Dot net 4.5 era, nobody will follow this way.

Code snippet to achieve this:

internal static string GetFeed()
{
HttpWebRequest request = HttpWebRequest.Create(@"http://rss.news.yahoo.com/rss/entertainment") as HttpWebRequest;
WebResponse response = request.GetResponse();
Stream responseStream =  response.GetResponseStream();
return new StreamReader(responseStream).ReadToEnd();
}

AsyncCallback - UI will be responsive, but code becomes bulky with extra overhead of callbacks. Before introducing the async and await keywords, this way was very useful to achieve Asynchrony.

Code snippet to achieve this:

internal static void GetFeedUsingAsyncCallback()
        {
 HttpWebRequest request = HttpWebRequest.Create(@"http://rss.news.yahoo.com/rss/entertainment") as HttpWebRequest;
             request.BeginGetResponse(new AsyncCallback(OnGetResponse), request);
        }
  private static void OnGetResponse(IAsyncResult ar)
        {
            HttpWebRequest myHttpWebRequest = ar.AsyncState as HttpWebRequest;
            WebResponse response = (HttpWebResponse)myHttpWebRequest.EndGetResponse(ar);
            // Read the response into a Stream object.
            Stream responseStream = response.GetResponseStream();
            string content = new StreamReader(responseStream).ReadToEnd();

            //Raise event here
        }

Async and Await
·         Responsive UI
·         Clean code
·         Debugging becomes easier as sequential control flow.

Code snippet to achieve this:

 async internal static  Task<string>  GetFeedAsync()
     {
HttpWebRequest request = HttpWebRequest.Create(@"http://rss.news.yahoo.com/rss/entertainment") as HttpWebRequest;
WebResponse response = await request.GetResponseAsync();         
            Stream responseStream = response.GetResponseStream();

            return await new StreamReader(responseStream).ReadToEndAsync();
        }

Assume if Async method is not available, how we will convert it to async method?

async internal static Task<string> GetStringAsyncExtesion(this HttpWebRequest request)
        {
TaskCompletionSource<string> taskCompletionSource = new TaskCompletionSource<string>();

          
                await Task.Run(() =>
                               {
                                  try
                                 {
                                   WebResponse
                                       response = request.GetResponse();

                                   Stream responseStream = response.GetResponseStream();
                                   string result = new StreamReader(responseStream).ReadToEnd();
                                   taskCompletionSource.SetResult(result);
                                    }
                                    catch (Excecption ex)
                                    {
                                        taskCompletionSource.SetException(ex);
                                    }
                               });
           
          
            return await taskCompletionSource.Task;
 }

Use above created new async method as follows:
static internal Task<string> GetStringExplictAsync()
        {
HttpWebRequest request = HttpWebRequest.Create(@"http://rss.news.yahoo.com/rss/entertainment") as HttpWebRequest;

            return request.GetStringAsyncExtesion();
        }
Pl. Provide your comments on this post.

Wednesday, September 10, 2014

Serialization behind the scene

In the post I am going to explain about the Binary Serialization internals.


With the Binary Serialization we can serialize any fields (Private, protected or public) which are not marked as NonSerializableAttribute.

FCL providers Formatter services and Formatters like BinaryFormatters to achieve serialization.
FormatterServices class provides some static methods to achieve Serialization and De-Serialization behind the scene , which are intern called by the Serialize and de-serialize methods of BinaryFormatter.

Let us look at the following Steps how Serialization and De-Serialization works using FormatterServices static methods.

Serialization:
·         public static MemberInfo[] GetSerializableMembers(
        Type type
        )
This method uses the reflection to get all the (private and public) instance fields and returns MemberInfo array.
·         The object being serialized and MemberInfo array passed to static method GetObjectData(Object obj, MemberInfo[] members). This methods returns array of objects where each element identifies the value of the field in the object being serialized.
·         Finally, the formatter then enumerates over the elements in the two arrays, writing each member's name and value to the byte stream.

De-Serialization:

·         public static Type GetTypeFromAssembly(
        Assembly assem,
        string name)
This method returns System.Type object indicating the type of object being De-Serialized

·         public static Object GetUninitializedObject(
        Type type)
This method allocates memory for the new object without calling constructor and all the object's bytes are initialized to null or 0.

·         The formatter now construct an object and initializes a MemberInfo array by calling GetSerializableMembers() method; This method returns set of the fields(Private and Protected also) that were serialized and that need to de-serialized.
·         The formatter now creates and initializes an object array from the data contained from the stream.
·         The reference to newly created object, MemberInfo array and object array data will be passed to PopulateObjectMembers (object obj, MemberInfo[] membrs, object[] data).
This method enumerates over the arrays, initializing each field to its corresponding value. At this point the object is completely De-serialized.

The above explanation is implemented in the below example.
Got help from:

 Special thanks to Jeffery Ritcher and MSDN for providing required internal details.

if any mistakes found in the blog, guide me correct direction