VB本身是不支援多線程的。但是VB中的部件有程序内及程序外的區分,是以這裡我使用程序外部件來實作異步調用。
伺服器端代碼,建立一個ActiveEXE工程,加入一個窗體,窗體中存放一個Timer控件
添加一個類子產品。代碼如下
Private WithEvents m_Timer As Timer
Public Event MyTaskResult(result As Long)
Private j As Long
Private Sub Class_Initialize()
Set m_Timer = Form1.Timer1
End Sub
Private Sub m_Timer_Timer()
m_Timer.Enabled = False
Dim i As Long
Dim r As Long
For i = 0 To j
r = r + i
Next
RaiseEvent MyTaskResult(r)
End Sub
Public Sub MyBigTask(i As Long)
m_Timer.Enabled = True
m_Timer.Interval = 10
j = i
End Sub
用戶端
Private WithEvents longTask As AsyncServerTest.MyAsyncCls
Private Sub Command1_Click()
Set longTask = New AsyncServerTest.MyAsyncCls
longTask.MyBigTask (Text1.Text)
End Sub
Private Sub longTask_MyTaskResult(result As Long)
Text2.Text = result
MsgBox "long task finished"
End Sub