Rules

Secret ingredients to quality software

Edit
Info

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

Created on 04 Dec 2009 | Last updated by System Account on 20 Oct 2010 08:56 AM (over 10 years ago)

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: Invoke web method by the normal way (Bad - 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: Invoke web method by using asynchronous method and CallBack (Good - 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

Adam CoganAdam Cogan
Ryan TeeRyan Tee

We open source. This page is on GitHub