BackgroundWorker 是一个不错的选择。无论您使用什么请注意,如果后台线程是处理器密集型的,即长时间运行的紧密循环,性能可能会受到影响。如果你有一个多核 CPU,这可能不是很明显。
这是一个简单的 Threading.Thread 示例。
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Button3.Enabled = False
'for example pass a string and an integer to a thread as an array
Dim params() As Object = {"one", 1} 'parameters for thread. object picked because of mixed type
Dim t As New Threading.Thread(AddressOf someThread)
t.IsBackground = True
t.Start(params) 'start thread with params
End Sub
Public Sub someThread(params As Object)
'not on the UI
Dim theparams() As Object = DirectCast(params, Object()) 'convert object to what it really is, an array of objects
Dim param1 As String = DirectCast(theparams(0), String)
Dim param2 As Integer = DirectCast(theparams(1), Integer)
Debug.WriteLine(param1)
Debug.WriteLine(param2)
showOnUI(param1)
End Sub
Public Sub showOnUI(s As String)
If Me.InvokeRequired Then
'not running on UI
Me.Invoke(Sub() showOnUI(s)) 'run method on UI
Else
'running on UI
Label1.Text = s
Button3.Enabled = True
End If
End Sub