如何在For循环中取消多个背景工作者?

时间:2018-08-30 00:06:56

标签: vb.net loops backgroundworker

在Visual Studio 15中创建Windows应用程序。 有一个表格,我最多可以启动10个后台工作任务(BG1至BG10)。我目前分别通过以下方式取消每个BGWorker:

Private Sub DSx10C_Click(sender As Object, e As EventArgs) Handles DSx10C.Click
    BackgroundWorker10.CancelAsync()
    BackgroundWorker10.Dispose()
    Label10.Text = "Cancelled"
End Sub

我需要执行“全部取消”选项。 如何在For循环中遍历所有10个BGWorker? 希望我的问题是更好的MCVE。

1 个答案:

答案 0 :(得分:0)

如何取消所有BackgroundWorkers

您可以这样做:      声明array中的BackgroundWorkers

Dim MyBackgroundWorkers() As BackgroundWorker
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    '' add all your BackgroundWorkers to the array
    MyBackgroundWorkers = New BackgroundWorker() {BackgroundWorker1, BackgroundWorker2, BackgroundWorker3, BackgroundWorker4, BackgroundWorker5}
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    '' now you can Cancel all of them in a loop
    For Each bgw In MyBackgroundWorkers
        If bgw.IsBusy Then
            bgw.CancelAsync()
        End If
    Next
End Sub

这是假设您的BackgroundWorkers是您在设计时从工具箱中添加的controls。如果已从代码中声明并添加了该代码,则需要在Form_Load代码中进行适当的修改。

尝试一下。希望这会有所帮助。