New features in the .NET Framework 4.x

In this section, we will take a look at the striking features in Microsoft .NET Framework 4.x.

Supporting asynchronous programming in .NET Framework 4.x

Asynchronous programming is a feature in Microsoft .NET Framework 4.5 that can enhance the overall responsiveness of your application. Support for asynchronous programming is inbuilt in Visual Studio 2012. Asynchronous tasks help write applications that are more responsive and provide a better user experience.

Method calls can either be synchronous or asynchronous. In a synchronous method call, the method is completed in its entirety by the currently executing thread. In an asynchronous method call on the other hand, the currently executing thread begins execution of the method and returns immediately—it doesn't block the user interface in any way. You can execute synchronous threads in Microsoft .NET Framework using the System.Threading.Thread namespace. Synchronous threads are those that are executed one after another, that is, in a sequence. In a synchronous operation, two or more threads run in a same context, and therefore the execution of one may block the other.

The support for asynchronous programming is made available through the keywords async and await. The usage of the keywords async and await enable you to implement asynchronous programming seamlessly—no callbacks, IAsyncResult, and so on. You can use these two keywords to create asynchronous methods. Note that the asynchronous methods can have three possible return types. These are:

  • Task<TResult>
  • Task
  • void

When await keyword is called against that particular task, the method of that task is immediately suspended, and the method resumes its execution once the execution of the task is complete.

Here is a code snippet that illustrates how asynchronous programming can be implemented in Microsoft .NET Framework 4.5:

async Task<int> CallWebPagesAsynchronously()
{ 
    HttpClient client = new HttpClient();
    Task<string> strTask = client.GetStringAsync("http://joydipkanjilal.com");
    DoSomeWork();
    string content = await strTask;
    return content.Length;
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset