When you want to consume your web service. It could take some time, to get the result back.
Because we want, to handle other methods in our code, during the process of invoking the WebMethod and getting back the result. We can invoke the WebMethod Asynchronously.
To invoke the web service asynchronously, we have to utilize the Begin(Method) and the End(Method).
In this is example, we are consuming a web service and we add a counter.
I've created a helloWorld method in my webservice. With a pause of 1000-milliseconds.
<WebMethod()> _
Public Function HelloWorld() As String
System.Threading.Thread.Sleep(1000)
Return "hello world"
End Function
Now create a new website and add a webreference to this web service.
Dim webservice As New localhost.Service
Dim myISyncResult As IAsyncResult
Dim iCounter As Integer = 0
Dim sResult As String = String.Empty
' after the request sent, we can use IAsyncResult. To check if we are still waiting for the response
myISyncResult = webservice.BeginHelloWorld(Nothing, Nothing)
' wait until the async request is completed
Do Until myISyncResult.IsCompleted = True
iCounter += 1
' call other functions
Loop
' get the result from the endMethod
sResult = webservice.EndHelloWorld(myISyncResult)
Response.Write("Result: " & sResult & _ "
Time: " & iCounter.ToString)
If you have to do other actions in your codebehind, it's very useful to consume your web service asynchronously!