如何启动Backgroundworker ByRef



我想给后台工作人员分配一个自定义名称,所以我创建了一个自定义类:

Public Class NamedBKW
Public BKW As BackgroundWorker
Public Name As String
Public Sub New(ByVal thisBKW As BackgroundWorker, ByVal thisName As String)
BKW = thisBKW
Name = thisName
End Sub
End Class

我有一个这些NamedBKWs的列表,我想通过循环来一次启动一个。该列表是在程序启动时生成的。

Friend Sub StartService()
[...]
BuildLists()
For x As Integer = 0 To ListOfBKWs.Count - 1
StartThisThread(ListOfBKWs(x).BKW, ListOfBKWs(x).Name)
Thread.Sleep(3000)
Next
End Sub
Public Sub BuildLists()
[...]
' List of BKWs:
' Note that the order listed here will determine the order they are started.
ListOfBKWs = New List(Of NamedBKW)
ListOfBKWs.Add(New NamedBKW(ScheduleCheckerBKW, "ScheduleChecker"))
ListOfBKWs.Add(New NamedBKW(BackupStage5BKW, "Stage 5"))
ListOfBKWs.Add(New NamedBKW(BackupStage4BKW, "Stage 4"))
ListOfBKWs.Add(New NamedBKW(BackupStage3BKW, "Stage 3"))
ListOfBKWs.Add(New NamedBKW(BackupStage2BKW, "Stage 2"))
ListOfBKWs.Add(New NamedBKW(BackupStage1BKW, "Stage 1"))
ListOfBKWs.Add(New NamedBKW(DeleteOldFilesBKW, "DeleteOldFiles"))
ListOfBKWs.Add(New NamedBKW(FixerBKW, "Fixer"))
ListOfBKWs.Add(New NamedBKW(ThreadCheckerBKW, "ThreadChecker"))
End Sub
Public Sub StartThisThread(ByRef thisBKW As BackgroundWorker, ByVal thisName As String)
NPC.WriteToConsoleAndLog("MAIN: Starting " & thisName & " thread...")
thisBKW = New BackgroundWorker
thisBKW.WorkerReportsProgress = True
thisBKW.WorkerSupportsCancellation = True
thisBKW.RunWorkerAsync()
End Sub

但由于某种原因,这并不奏效。控制台/日志会打印消息,说明它正在启动每个线程,但线程实际上并没有启动。我做错了什么?

所有的Backgroundworker都在主类中声明,如下所示:

Friend WithEvents BackupStage1BKW As New BackgroundWorker

您有这样的声明来创建后台工作对象:

Friend WithEvents BackupStage1BKW As New BackgroundWorker

然而,您所展示的内容中没有任何内容表明这些员工实际上做了任何事情。如果有一种方法可以为每个连接到WithEvents声明中的工作者处理DoWork事件,那么我们看不到它

我暂时假设这些方法确实存在,并且正确地订阅了事件。在这种情况下,我们来讨论下一个问题。这一行覆盖了声明的对象:

thisBKW = New BackgroundWorker

现在,您有了全新的对象,以前的任何事件处理程序都不再适用。

你真的不想要那行,也不想要这里的ByRef。请记住,ByVal仍然传递引用唯一的区别是它传递了引用的副本,结果证明这正是你大多数时候所需要的。

相关内容

  • 没有找到相关文章

最新更新