The Windows Communication Foundation (WCF) is an application programming interface in the .NET Framework for building connected, service-oriented applications. A WCF client has two ways to access the functions provided by WCF services. They are synchronous and asynchronous WCF calls. This article i wanna tell you how to asynchronous WCF service calls using .NET Framework 4.5. To demonstrate examples, I am using Windows 7 and Visual Studio 2010.

1. Open Visual Studio . It will create a Web service called MyAsync.asmx with a sample web method inside.


You can see the code snippet of the web method below: 

[WebMethod]
public string MyTestAsynchronousMethod(string strName, int
waitTime)
{
  System.Threading.Thread.Sleep(waitTime);
  return "Hei..." + strName + "Iam Called Asynchronously"; 
}

2. And also we create a consuming ASP.NET web application that looks like the below screenshot.



Now the only thing we have to do is call the web service in the button click event.

To call the application on the button click event we have to create a proxy. As all of you know we can create a proxy using WSDL.EXE and also by adding a web reference to the consuming application. Here I am going to use the second approach, i.e., using service reference for ease.

Right click the consuming web application, go to the Add Service Reference option, Then go ahead with adding the service reference in your consuming application. I have added a web reference in the consuming application with name MyProxy.

So we are all set to call the service from our button click.

In the asynchronous button click,I am going to create the proxy class object and looking at the intelisense, we can see that there are mainly three things related to our web method which we have created. 1 event and two methods,one with an async augment.

Here we are going to use the event called MyTestAsynchronousMethodCompleated and the web method MyTestAsynchronousMethodAsync.

You might think that from where the web method MyTestAsynchronousMethodAsync does and the event MyTestAsynchronousMethodCompleated came from, right ?
The answer is it will come by default while creating the proxy of the web service.

The web method MyTestAsynchronousMethodAsync is the hero who makes the asynchronous call happen and the event MyTestAsynchronousMethodCompleated is the supporting actor of the hero.

You can see the event and the method in the below snapshot.



3. The next thing we have to do is to plumb the event. As I mentioned earlier, the event is responsible to return the result after the execution of the web service method.  So I am going to set a label in our consuming application in such a way that it will display the returned string from the web service method call.
For that purpose I have added an event handler for that event. Visual Studio will create the event handler stub automatically for us. Just type += next to the event which we have and hit Tab key twice in your keyboard. You have got your event handler stub with the arguments and the parameters set. The only thing you have to do is write the business logic inside the event handler stub. That Visual Studio doesn't know, I mean your business logic.
This is the code :



4. You can see a property called Result in the event argument. That’s the property that gives you the web method executed Result, Error etc., in string format, it’s not the service method itself as before.
So let’s go and implement the logic in the stub by assigning the result to the label text property (you can see this in the below snapshot). We are going to call the second web method which is generated automatically.

namespace AsyncConsumer
{
    public partial class _Default : System.Web.UI.Page
    {
        Stopwatch objSW = new Stopwatch();
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void BtnAsync_Click(object sender, EventArgs e)
        {
            objSW.Reset();
            objSW.Start();
            MyProxy.MyAsync objProxy = new MyProxy.MyAsync();
            objProxy.MyTestAsynchronousMethodCompleted += 
              new MyProxy.MyTestAsynchronousMethodCompletedEventHandler(
              objProxy_MyTestAsynchronousMethodCompleted);
            objProxy.MyTestAsynchronousMethodAsync(txtName.Text, 
              Convert.ToInt32(txtWaitTime.Text));
            DoSomeLongJob();
            lblExecTime.Text = "Total Execution Time :" + 
              objSW.ElapsedMilliseconds.ToString() + " Milliseconds";
        }
        void objProxy_MyTestAsynchronousMethodCompleted(object sender, 
             MyProxy.MyTestAsynchronousMethodCompletedEventArgs e)
        {
            lblResult.Text = e.Result;
        }
        private void DoSomeLongJob()
        {
            System.Threading.Thread.Sleep(5000);
        }
    }
} 


5. I have added a method called DoSomeLongJob(). Which makes the thread to wait for 5 seconds for the consuming application and a Label to display the execution time.The above is the complete code snippet which we have done.
Let’s see the execution of our application.



What would be the result and execution time?
In a normal case this will take approximately 7 seconds delay, that is 2 seconds which we have given, and the 5 seconds of the DoSomeLongJob();
right?

Let’s see how long will it take. 

Ooopsss!!! Unfortunately or fortunately I got an exception like below while clicking the button:



6. Did you notice the marked portion in the exception?
Yes, we have to add and set the Async attribute to true in the Page directive of the page in which we are planning to have any asynchronous web service method call. Otherwise it’s not possible. Let’s go and set it.

After setting the Async attribute the directive will be like:



7. And the last, reload your page.