關於webservice的異步調用簡單實例
無論在任何情況下,被調用方的代碼無論是被異步調用還是同步調用的情況下,被調用方的代碼都是一樣的,
下面,我們就以異步調用一個webservice 為例作說明。
這是一個webservice
<WebMethod(Description:="試驗")> _
Public Function delCurTable(ByVal tbName As String) As Boolean
Try
Return True
Catch ex As Exception
Return False
End Try
End Function
關於這個webservice的同步調用方法,我就不做說明了
異步調用:
Private a As vbwebservice.DataManage'定義一個webservice變量
Dim ar As IAsyncResult
public sub Callback1(byval ar as IAsyncResult)
''這裡可以不寫任何代碼
'這裡的代碼在調用方運行結束後,開始運行
end sub
#region "異步調用"
private sub btnStart_Click()
dim cb as asyncallback=new asyncallback(address(me.callback1))
ar=a.begindelcurtable("zdf",cb,a)
end sub
private sub btnEnd_Click()
if ar is nothing then
exit sub
end if
if ar.IsCompleted Then
dim m as boolean=a.enddelcurtable(ar)
messagebox.show(m.tostring)
end if
end sub
#end region
注意:“返回異步調用的結果一次只能調用一次,如果想再執行一遍,就必須重新執行一遍begin的方法”
以上是vb.Net的用法,下面是c#的用法
CWebService.DataManage a;
System.IAsyncResult ar;
private void Form1_Load(object sender, System.EventArgs e)
{
a=new CWebService.DataManage();
}
public void CallBack1(System.IAsyncResult ar)
{
}
private void btnStart_Click(object sender, System.EventArgs e)
{
System.AsyncCallback cb=new AsyncCallback(this.CallBack1);
ar=a.BegindelCurTable("zhang",cb,a);
}
private void btnEnd_Click(object sender, System.EventArgs e)
{
if(ar==null)
{
MessageBox.Show("null");
return ;
}
if(ar.IsCompleted )
{
bool m=a.EnddelCurTable(ar);
MessageBox.Show(m.ToString());
}
else
{
MessageBox.Show("為完成");
}
}