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!

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read