异步调用Webservice的方法及实例代码如下:
主方法(调用Webservice的方法):
ArrayList al = new ArrayList();
localhost.TestService ts = new TestWebPro.localhost.TestService();//这是Webservice在本地的代理类
System.Threading.ManualResetEvent mre = new System.Threading.ManualResetEvent(false);
al.Add(ts);
al.Add(mre);
//执行异步调用,localhost.TestEnum.bus是自定义的枚举,用做调用方法的参数
System.IAsyncResult ar = ts.BeginTestMethod(localhost.TestEnum.bus,new System.AsyncCallback(this.EndCall),al);
//.执行其它操作
mre.WaitOne();//等待调用完成
//.继续执行其它操作
localhost.TestService ts = new TestWebPro.localhost.TestService();//这是Webservice在本地的代理类
System.Threading.ManualResetEvent mre = new System.Threading.ManualResetEvent(false);
al.Add(ts);
al.Add(mre);
//执行异步调用,localhost.TestEnum.bus是自定义的枚举,用做调用方法的参数
System.IAsyncResult ar = ts.BeginTestMethod(localhost.TestEnum.bus,new System.AsyncCallback(this.EndCall),al);
//.执行其它操作
mre.WaitOne();//等待调用完成
//.继续执行其它操作
回调方法EndCall(调用完成后执行的方法):
public void EndCall(System.IAsyncResult ar)
{
try
{
ArrayList al = (ArrayList)ar.AsyncState;
localhost.TestService ts = (localhost.TestService)al[0];
System.Threading.ManualResetEvent mre = (System.Threading.ManualResetEvent)al[1];
string s = ts.EndTestMethod(ar);//获得调用结果
mre.Set();//通知主方法可以继续执行
}
catch(Exception ex)
{
throw ex;
}
}
{
try
{
ArrayList al = (ArrayList)ar.AsyncState;
localhost.TestService ts = (localhost.TestService)al[0];
System.Threading.ManualResetEvent mre = (System.Threading.ManualResetEvent)al[1];
string s = ts.EndTestMethod(ar);//获得调用结果
mre.Set();//通知主方法可以继续执行
}
catch(Exception ex)
{
throw ex;
}
}
如果主方法和回调方法在同一个类就可以把ts和mre声明成私有全局变量,而不用通过IAsyncResult.AsyncState来传递到回调函数中。