懶人的 vb.net Thread 運用方式
Imports System.Threading
Namespace Classes
Public Class BkWorker
Delegate Sub BkWorkerDelegate(ByVal Params As Object)
Private m_Thread As Thread = Nothing
Private m_Controler As Control = Nothing
Private m_Params As Object = Nothing
Public Event BkWorkerToDo(ByRef Params As Object)
Public Event BkWorkerInvoke(ByVal Params As Object)
Dim CallBackInvoke As New BkWorkerDelegate(AddressOf BkWorker_Invoke)
Public Sub New(ByVal ctrl As Control)
m_Controler = ctrl
End Sub
Public Sub Start()
Dim ThreadBegin As New ThreadStart(AddressOf BkWorker_ToDo)
Me.m_Thread = New Thread(ThreadBegin)
Me.m_Thread.IsBackground = True
Me.m_Thread.Name = "BkWorkerThread" + Now.ToShortTimeString()
Me.m_Thread.Start()
End Sub
Private Sub BkWorker_ToDo()
RaiseEvent BkWorkerToDo(m_Params)
m_Controler.Invoke(CallBackInvoke, m_Params)
End Sub
Private Sub BkWorker_Invoke(ByVal Params As Object)
RaiseEvent BkWorkerInvoke(Params)
End Sub
End Class
End Namespace
使用方式:
Private Sub LoadData()
Dim bk As New BkWorker(Me)
Try
'連結要丟到背景工作的副程式
AddHandler bk.BkWorkerToDo, AddressOf DoQueryDataBase
'工作完畢後, 所要處理資料(與UI互動)
AddHandler bk.BkWorkerInvoke, AddressOf BindData
bk.Start()
Finally
bk = 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