Tuesday, August 09, 2005

Are you ever faced with a problem that you have to call a webservice from you C# windows application and the webservice is taking some time in returning the data? The user has to wait until the webservice returns. The user will be stuck until the webservice replies back, but what if you can't afford such delay. So here is the solution for that. Call the webservice asynchronously. Seems confused…… how to do it? It is not that hard, when you enter the reference of the webservice in your project it automatically creates methods for calling the webservice asynchronously

Two methods are created by default one is to start the webmethod asynchronously and other is to end the asynchronous call.


Sample Web Service:

public class AddService
{
[webmethod]
public int Add (int a,int b)
{
return a+b;
}
}

Sample Client:

public Class AddClient
{

private AddService serviceObject = null;

public AsyncCallback wsCallBack = null;

public void DisplayResults()
{
if ( wsCallBack == null )
{
wsCallBack = new AsyncCallback (AddResults);
}
serviceObject.BeginAdd(5,6,wsCallBack, new ReturnValue());

//Continue to do whatever you want to do
}
//This function is called when the Add webmethod returns
public void AddResults(IAsyncResult asyn)
{
ReturnValue rValue = (ReturnValue)asyn.AsyncState ;
int result = rValue.result; //this gives you the result
serviceObject.EndAdd(asyn);
}
}
//This call is used to represent the return value from the webmethod
Public Class ReturnValue
{
public int result;
}

No comments: