VB.net Thread執行序簡單應用

  • 透過本範例,將耗時的工作挪到背景另外執行,如:資料庫搜尋、Socket連線傳輸等

建立一個Class用來執行新的Thread

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
Imports System.Threading

Namespace Classes
Public Class Worker
Delegate Sub WorkerDelegate(ByVal Params As Object)
Private m_Thread As Thread = Nothing
Private m_Controler As Control = Nothing
Private m_Params As Object = Nothing
Public Event WorkerToDo(ByRef Params As Object)
Public Event WorkerInvoke(ByVal Params As Object)
Dim CallBackInvoke As New WorkerDelegate(AddressOf Worker_Invoke)

Public Sub New(ByVal ctrl As Control)
m_Controler = ctrl
End Sub

Public Sub Start()
Dim ThreadBegin As New ThreadStart(AddressOf Worker_ToDo)
Me.m_Thread = New Thread(ThreadBegin)
Me.m_Thread.IsBackground = True
Me.m_Thread.Name = "WorkerThread" + Now.ToShortTimeString()
Me.m_Thread.Start()
End Sub

Private Sub Worker_ToDo()
RaiseEvent WorkerToDo(m_Params)
m_Controler.Invoke(CallBackInvoke, m_Params)
End Sub

Private Sub Worker_Invoke(ByVal Params As Object)
RaiseEvent WorkerInvoke(Params)
End Sub
End Class
End Namespace

使用方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Private Sub LoadData()
Dim wk As New Worker(Me)
Try
'連結要丟到背景工作的副程式
AddHandler wk.WorkerToDo, AddressOf DoQueryDataBase
'工作完畢後, 所要處理資料(與UI互動)
AddHandler wk.WorkerInvoke, AddressOf BindData
wk.Start()
Finally
wk = Nothing
End Try
End Sub

Private Sub DoQueryDataBase(ByRef Params As Object)
'執行的程式, 結果可由 Params 代傳
'1: Params = modADO.Query(...)
'2: Params = New Object() {data1, data2, ...}
End Sub

Private Sub BindData(ByVal Params As Object)
'背景工作完畢後, 與 UI 互動
TextBox1.Text = CInt(Params)
End Sub