Using WCF Async Operations

Consuming a WCF Service is pretty straight forward. What if we want to call a service operation which takes some time to complete? We need some asynchronous process to handle operation calls. This can enabled by checking ‘Generate asynchronous operations’ in the service reference settings dialog.

This setting creates the typical begin and end pairs of async operation methods to the Client Proxy class as show below. In this case BeginEcho and EndEcho. Besides that we also get another async operation method calles EchoAsync. This method works in conjunction with the EchoCompleted event.

Echo Service Client Object Browser

Now we can call EchoAsync just like we called Echo before. Instead of waiting for the result to come back from the service, the result gets handled asynchronously in the ChannelEchoCompleted event handler.

using System;
using EchoClientConsole.EchoServiceReference;

namespace EchoClientConsole
{
    internal class Program
    {
        private static void Main()
        {
            var channel = new EchoServiceClient(
                "WSHttpBinding_IEchoService"
                );

            channel.EchoCompleted += ChannelEchoCompleted;
            channel.EchoAsync(new EchoMessage {Text = "Hey Async "});

            Console.WriteLine("Async operation called...");
            Console.ReadLine();

            channel.Close();
        }

        private static void ChannelEchoCompleted(
            object sender, EchoCompletedEventArgs e)
        {
            EchoMessage echoMessage = e.Result;
            Console.WriteLine(echoMessage.Text);
        }
    }
}

Wcf Async Operation Console

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>