Asynchronous Calls to Web Services

A normal synchronous call to a Web Service blocks the application till it receives the response from the Web Service. This is not a problem when the application is deployed in a private network with plenty of bandwidth. The problem could arise when the call is made over the Internet where the delay can be quite lengthy.


The solution is to call the Web Service asynchronously. Doing so enables us to call the web service on a separate thread, which allows us to continue our normal processing while the web service responds. There are a few ways to do the same. We will do so using Callbacks.


We have created a simple calculator web service, which has the following methods.

·        Add

·        Subtract

·        Multiply

·        Divide

The code for the same is given below.


<%@ WebService language="C#" class="Calculator" %>


using System;

using System.Web.Services;

using System.Xml.Serialization;


public class Calculator {



    public int Add(int a, int b)


        return a + b;



    public int Subtract(int a, int b)


        return a - b;



    public int Multiply(int a, int b)


        return a * b;



    public int Divide(int a, int b)


        return a/b;





As a client for this web service, we will look at a windows forms client. The code for the same is given below.


Asynchronous calls are made by calling the BeginAdd method instead of a call to the Add method. The response is received by calling the EndAdd method in the callback event which is handled by a delegate method.


Imports Test.Calculator


Public Class Form2

    Inherits System.Windows.Forms.Form


    'CallBack object is initialized with the

    'reference of the Delegate method

    Dim oCB As New AsyncCallback(AddressOf CallBack)

    ' Proxy of the calculator web service.

    Dim oCalc As Calculator.Calculator


    Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        oCalc = New Calculator.Calculator

        MessageBox.Show("Form is loaded")

        'The call to the Web Service is given.

        oCalc.BeginAdd(5, 10, oCB, Nothing)

        'Further Processing continues till the web service responds

        MessageBox.Show("Calculator.BeginAdd is called")

    End Sub

    'The Delegate method which receives the response from

    'the web service

    Private Sub CallBack(ByVal Result As IAsyncResult)

        Dim iRes As Integer

        iRes = oCalc.EndAdd(Result)


    End Sub


End Class



This was created using VS.NET, the Designer Code has been removed for simplicity. It is also assumed that a Web Reference or a Web service proxy has been created.


Happy Coding!!!        


Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.