VB2008异步调用WebService

下面将通过一个窗体程序和本站提供的Web服务来演示如何用VB2008异步调用WebService

1、首先创建一个WindowsApplication

2、添加一个WebService的引用(本Demo中使用的是http://webservice.lishewen.com.cn/EvalService.asmx

注意在WebService引用的高级选项中勾选(Generate asynchronous operations)

3、设计好窗体

4、相关的代码如下:

Public Class Form1

    Private BeginTime, EndTime As DateTime
    Private TimeBeginToEnd As TimeSpan

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        '实例化Web服务
        Dim wb As New LSWEvalService.算神工作室表达式计算服务SoapClient
        '执行完成的委托
        AddHandler wb.EvalCompleted, AddressOf wb_EvalCompleted
        BeginTime = Now
        If Not String.IsNullOrEmpty(TextBox1.Text) Then
            'WebService方法的异步调用
            wb.EvalAsync(TextBox1.Text)
        Else
            MsgBox("请输入表达式")
        End If
    End Sub

    'Eval方法执行完成后触发
    Private Sub wb_EvalCompleted(ByVal sender As Object, ByVal e As LSWEvalService.EvalCompletedEventArgs)
        EndTime = Now
        '计算时间差
        TimeBeginToEnd = EndTime - BeginTime
        Label1.Text = TimeBeginToEnd.TotalSeconds & "秒"
        TextBox2.Text = e.Result
    End Sub

End Class

源代码打包下载: LSWServiceTest.rar (85.87 kb)