Thursday, March 29, 2012

What's new in C# 5.0

As some of you might already know the beta release of Visual Studio version 11 which includes the C# version 5, Visual Basic version 11 and .NET CLR version 4.5 is available for download now.

On this week's MVP Mondays series Fahao Tang, one of the Visual C# MVPs' in the community has published this nice little article on Introduction of New Features in C# 5.0. Thought to share it with you all and add something along which I have learned while experiencing the beauty of Visual Studio Async CTP.

In C# 5.0 there are two main new key features,
  1. Async Programming
  2. Caller Information
01. Async Programming

Microsoft has introduced this Async Programming or Asynchronous Programming with two keywords. One is async modifier and the other is await operator. With this new approach, asynchronous and concurrent programming will be much easier and the code would be easier to write, easier to understand and maintain.

async

The async modifier indicates the compiler that a method or a lambda expression is asynchronous. A method that is marked with the async modifier is referred to as an async method. An async method typically contains one or more occurrences of the await operator, but the absence of an operator does not cause a compiler error. Instead the compiler issues a warning for such methods. If an async method doesn’t use the await operator, the method will not be suspended and will be executing as a synchronous method, despite the async modifier.

Important thing to note with async methods is, an async method can have only following return types : void, Task and Task(Of TResult).
private async void btnStart_Click(object sender, RoutedEventArgs e)
await

Inside an async method, the await operator is applied to a task to suspend execution of the method until the task is completed (which means await requires a task (using System.Threading.Tasks) to await on). In the meantime, control is returned to the caller of the method. The suspension is accomplished without exiting the async method, and it does not cause finally blocks to run. 

The things to note here is if we use try catch block, try catch block is capable of handling any exception occurring in caller or in the async method without any extra work.

To take the concept clearly let's take a look at the following code.
private void btnStart_Click(object sender, RoutedEventArgs e)
{   
    //call one
    var result = GetContent("http://msdn.microsoft.com/");
    //call two
    var result = GetContentAsync("http://msdn.microsoft.com/");               

    //some code here
}
private string GetContent(string address)
{   
    try
    {
        string result = new WebClient().DownloadString(address);
        return result;
    }
    catch (Exception ex)
    {
        throw;
    }
}
The above button click event would be a general button click event where the whole code will be executing line by line. When the event get fired our code will call the GetContent method and will download the all the html content in "http://msdn.microsoft.com/" as a string and it will get stored in the string variable result and it will be returned to the caller. Then we can do what ever we want to do with that. The core point in the above way is, the execution of line "//some code here" will hold until the download completes. In that time if you try to move your application across your desktop or if you click on your application you will see that your application gets unresponsive.

For that here comes async and await. You can mark your method async and you can change the DownloadString to it's asynchronous type which is DownloadStringTaskAsync. Now since await always requires a task to await on and DownloadStringTaskAsync will return a task you can easily put await and modify the code like this.Now what will happen is, when the event get fired our code will call the GetContent method and will download the all the html content in "http://msdn.microsoft.com/" in the background while executing next lines continuously which are in "//some code here". So when you move your application across your desktop or if you click on your application there will be no hang outs or unresponsive messages.
private async Task<string> GetContentAsync(string address)
{   
    try
    {
        return await new WebClient().DownloadStringTaskAsync(address);
    }
    catch (Exception ex)
    {
        throw;
    }
}
02. Caller Information

Using this new feature we will be able obtain information about the caller of a method. This is possible via Caller Info attributes, using that we can identify the file path of the caller's source code, the line number in the caller's source code, and the member name of the caller. This information is helpful for tracing, debugging, and creating diagnostic tools.


For more information,
     What's New for Visual C# in Visual Studio 11 Beta

Happy Coding.

Regards,
Jaliya

2 comments:

  1. This is much better than official TAP documentation.

    ReplyDelete