Building and Consuming Async WCF Services in .NET Framework 4.5

In .NET Framework 4.5 the async and await keywords are pretty good additions. In this article I am going to explain on how simple is to build and consume WCF services using async and await keywords in .NET Framework 4.5. I will also provide the code examples of how the asynchrony was done in the previous versions of .NET Framework.

Significance of Async and Await Keywords

The difference that the async and await keywords bring to asynchronous programming is that the code is simpler to understand and follows the same hierarchy as a synchronous code. It avoids the complexities of using callbacks and also provides more control over the asynchronous process as it is task based.

Async – A method declared with async can perform await operations.

Await – Perform await over an asynchronous task.

You can read more about these keywords in Introduction to Async and Await Keywords in C# 5.0.

Sample Newsfeed WCF Service

Create a WCF service named FeedService.svc to a web application and host it to IIS. In the service contract, IFeedService.cs, add the code as follows.

namespace MyWcfServiceApplication
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IFeedService" in both code and config file together.
    [ServiceContract]
    public interface IFeedService
    {
        [OperationContract]
        List<string> GetGeneralNewsFeed();
 
        [OperationContract]
        List<String> GetSportsNewsFeed();
    }

}

Now let us go and add the implementation for the two service methods GetGeneralNewsFeed and GetSportsNewsFeed. FeedService.svc.cs concrete class code is as follows.

 
namespace MyWcfServiceApplication
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "FeedService" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select FeedService.svc or FeedService.svc.cs at the Solution Explorer and start debugging.
    public class FeedService : IFeedService
    {
 
        #region IFeedService Members
 
        public List<string> GetGeneralNewsFeed()
        {
            //Delay a bit and return some sample news content
            //Consider the delay as the time taken for parsing the feed in real time
            Thread.Sleep(3000);
            return new List<string>() { "This is general news number 1", "This is general news number 2", "This is general news number 3" };
        }
 
        public List<string> GetSportsNewsFeed()
        {
            //Delay a bit and return some sample news content
            //Consider the delay as the time taken for parsing the feed in real time
            Thread.Sleep(3000);
            return new List<string>() { "Some cricket news...", "Some soccer news..."};
        }
 
        #endregion
    }

}

I have used Thread.Sleep in order to simulate a delay in returning the feed data.

Consuming the WCF Service in the Client

You will also notice there won't be any changes with respect to the way the WCF service is built. It is all to do with the client proxy generation. Now create the client console application and Add service reference to the WCF service.

Older Method – Callbacks

In this section let us see the sample client code to know how the asynchronous WCF calls were made in the earlier versions of .NET Framework. Below is the client code, which uses callbacks.

namespace OldAsyncWay
{
    class Program
    {
        static FeedServiceClient client;
        static void Main(string[] args)
        {
            client = new FeedServiceClient();
            //Begin asynchronous service callsd and provide callback functions
            client.BeginGetGeneralNewsFeed(GeneralNewsCallback, null);
            client.BeginGetSportsNewsFeed(SportsNewsCallback, null);
            Console.ReadLine();
        }
 
        private static void GeneralNewsCallback(IAsyncResult asyncResult)
        {
            string[] generalNews = client.EndGetGeneralNewsFeed(asyncResult);
        }
 
        private static void SportsNewsCallback(IAsyncResult asyncResult)
        {
            string[] generalNews = client.EndGetSportsNewsFeed(asyncResult);
        }
    }
}

A begin and end calls for each service method, a call back definition and asyncResult object; all these increase the complexity of the code written.

Async Calls – Async and Await

With .net framework 4.5 you have the power of using async and await keywords. All you need to do is when adding the service reference go to the Advance service settings and select the option to generate task-based operations. This will take care of adding the Async methods to the proxy class. It will append the word Async as suffix to the actual service method. Fig 1.0 shows the option selected while adding the service reference.

Service Reference Settings
Fig 1.0 - Service Reference Settings

Following is the client code that consumes the WCF methods asynchronously using async and wait keywords.

namespace NewsClient
{
    class Program
    {
        static void Main(string[] args)
        {
            FetcNewsAsync();
            Console.ReadLine();
        }
 
        private static async void FetcNewsAsync()
        {
            FeedServiceClient client = new FeedServiceClient();
 
            //Makes a first async service call
            var task1 = client.GetGeneralNewsFeedAsync();
            //Makes the second async service call and doesn't wait for task1 completion
            var task2 = client.GetSportsNewsFeedAsync();
 
            //Now awaits for task1
            string[] generalNews = await task1;
            //awaits for task2
            string[] generalSports = await task2;
        }
    }

}

The code is now clean and simpler as that of a synchronous code. Hope this article explained clearly about consuming WCF services using async and await keywords in .NET Framework 4.5.

Happy reading!



Related Articles

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • VMware vCloud® Government Service provided by Carpathia® is an enterprise-class hybrid cloud service that delivers the tried and tested VMware capabilities widely used by government organizations today, with the added security and compliance assurance of FedRAMP authorization. The hybrid cloud is becoming more and more prevalent – in fact, nearly three-fourths of large enterprises expect to have hybrid deployments by 2015, according to a recent Gartner analyst report. Learn about the benefits of …

Most Popular Programming Stories

More for Developers

RSS Feeds