0

I have a form that loads just fine, and I'm trying to fire off a task using a Background Worker as it loads.

I'm getting no errors with the code below, but the bw.DoWork event doesn't seem to be firing.

Am I missing something here? Thanks.

Here is my form Class -

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

Here is my BackgroundWorker Class -

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
David Gard
  • 11,225
  • 36
  • 115
  • 227
  • 2
    all you did was create it. you forgot to invoke a `RunWorker` method – Ňɏssa Pøngjǣrdenlarp Dec 11 '13 at 16:42
  • 1
    Missing the call to RunWorkerAsync, but please [check with this q/a](http://stackoverflow.com/questions/1731384/how-to-stop-backgroundworker-on-forms-closing-event), you could have problems with a running BackgroundWorker when form is closing – Steve Dec 11 '13 at 16:45
  • @Steve - Thanks. It's early days yet, but I do plan to ensure the BackgroundWorker is not active when the form closes. – David Gard Dec 11 '13 at 16:46

1 Answers1

3

add to MyWorker constructor ('new' method) this line:

 bw.RunWorkerAsync()
Ňɏssa Pøngjǣrdenlarp
  • 38,411
  • 12
  • 59
  • 178
dovid
  • 6,354
  • 3
  • 33
  • 73