弄清楚了。
为了完整和参考,有两种方法可以做到这一点。一种是通过以下方式调用潜艇BackgroundWorker DoWork
:
Public Class Form1
Dim var1 As Integer = 0
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Run background worker
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
'Run task 1
Task1_Code()
'Run task 2
Task2_Code()
'Show variable
MessageBox.Show(var1)
End Sub
Sub Task1_Code()
'Wait 10 seconds
Threading.Thread.Sleep(10000)
'Sets var1 to 5
var1 = 5
End Sub
Sub Task2_Code()
'Wait 10 seconds
Threading.Thread.Sleep(10000)
'Same as var1= var1*5
var1 *= 5
End Sub
End Class
另一种是使用Task
类。
Imports System.Threading.Tasks
Public Class Form1
Dim var1 As Integer = 0
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
'Dim the task list and start excecuting
Dim task1 As task = Task.Factory.StartNew(AddressOf Task1_Code).ContinueWith(AddressOf Task2_Code)
'Waits for tasks to complete within 90 seconds or less
task1.Wait(90000)
'Shows variable
MessageBox.Show(var1)
End Sub
Sub Task1_Code()
'Wait 10 second
Threading.Thread.Sleep(10000)
'Sets var1 to 5
var1 = 5
End Sub
Sub Task2_Code()
'Wait 10 second
Threading.Thread.Sleep(10000)
'Same as var1= var1*5
var1 *= 5
End Sub
End Class
有关任务的更多信息,请参阅关于使用 vb.net 的顺序任务的帖子。