Do you use Asynchronous method and CallBack when invoke web method?

Last updated by Brady Stroud [SSW] over 1 year ago.See history

Web service and web invoking becomes more and more popular today as the distributed systems are widely deployed. However, the normal method invoking may cause a disaster when apply to web method because transmitting data over Internet may cause your program to hang for a couple of minutes.

private static string LoadContentFromWeb(string strUri) 

     { 
     ... 

WebResponse response = request.GetResponse(); 

     ...
     }

::: Figure: Bad example - Invoke web method by the normal way (because this will hang your UI thread)
:::

The correct way to invoke web method is using asynchronous call to send a request and use the delegated CallBack method to read the response, see code below:

public static void GetOnlineVersionAsync(string strUri) 
     { 
         try
         {
          ...

IAsyncResult r = request.BeginGetResponse(new AsyncCallback(ResCallBack), request);
          }
          catch(WebException ex)
         {
             Console.WriteLine(ex.ToString()) ; 
          }
     }

     private static void ResCallBack(IAsyncResult ar)
     {
        try
        {
      string content = string.Empty;

          WebRequest req = (WebRequest)ar.AsyncState;

          WebResponse response = req.EndGetResponse(ar);

           ...

           RaiseOnProductUpdateResult(content);

        }
        catch(WebException ex)
        {
           Console.WriteLine(ex.ToString());
           RaiseOnProductUpdateResult(string.Empty);
         }
     }

Figure: Good example - Invoke web method by using asynchronous method and CallBack (UI thread will be free once the request has been sent)

When working with Web Service, asynchronous methods will be automatically generated by your web services proxy.

Figure: Automatically generated asynchronous methods

We open source. Powered by GitHub