- 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