BackgroundWorker'DoWork'事件未触发

时间:2013-12-11 16:38:42

标签: vb.net backgroundworker

我有一个加载很好的表单,我正在尝试使用后台工作程序在加载时启动任务。

我的代码没有错误,但bw.DoWork事件似乎没有被触发。

我在这里遗漏了什么吗?感谢。

这是我的表格 -

Public Class mainForm

    Dim objWorker As MyWorker

    Private Sub mainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Call Me.loadForm()
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Call Me.closeForm()
    End Sub

    Private Sub loadForm()

        Me.objWorker = New MyWorker ' Invoke the background worker

    End Sub

    Private Sub closeForm()

        Me.objWorker.bw_Cancel()    ' Cancel the background worker
        Me.Close()                  ' Close the form

    End Sub

End Class

这是我的BackgroundWorker类 -

Imports System.ComponentModel

Partial Public Class MyWorker

    Private bw As BackgroundWorker = New BackgroundWorker

    Public Sub New()

        bw.WorkerReportsProgress = False
        bw.WorkerSupportsCancellation = True
        AddHandler bw.DoWork, AddressOf bw_DoWork
        AddHandler bw.RunWorkerCompleted, AddressOf bw_RunWorkerCompleted

    End Sub

    Private Sub bw_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)

        Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
        For i = 1 To 10
            If bw.CancellationPending = True Then
                e.Cancel = True
                Exit For
            Else
                System.Threading.Thread.Sleep(500)
                MsgBox("iteration " & i)
            End If
        Next

    End Sub

    Private Sub bw_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
        MsgBox("Complete!")
    End Sub

    Public Sub bw_Cancel()
        If bw.WorkerSupportsCancellation = True Then
            bw.CancelAsync()
        End If
    End Sub

End Class

1 个答案:

答案 0 :(得分:3)

添加到MyWorker构造函数('new'方法)这一行:

 bw.RunWorkerAsync()