我希望在后台线程中运行顺序子过程。我想知道是否允许这样做是通过创建一个后台工作者然后分别调用每个程序...
Private Sub BGW_DoWork(ByVal sender As System.Object, ByVal e As DoWorkEventArgs)
_Handles BGW.DoWork
Procedure1()
Procedure2()
Procedure3()
End Sub
这会在后台线程中运行每个过程吗?
此外,阅读其他帖子,其中一些建议使用List<svnCommand>
并将其传递给C#中的RunWorkerAsync
,而其他人建议使用Tasks
方法,这两种方法我都不知道。这两个中的任何一个都会起作用吗?
答案 0 :(得分:2)
不,没有必要将每个子例程放在自己的BackgroundWorker中。我经常从我的DoWork处理程序中调用多个子例程。从该处理程序调用的任何子例程都将在后台线程中执行。
答案 1 :(得分:2)
想出来。
要获得完整的完整性和参考,有两种方法可以做到这一点。一个是通过调用来自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
有关任务的更多信息,请转到sequential tasks using vb.net上的帖子。