How to stop a background worker vb.net

Corey_Steinwand
Corey_Steinwand used Ask the Experts™
on
How can I stop the background worker in this code when I click the btnStop
Imports System.Net.Mail
Imports System.IO
Imports System.Threading
Imports System.Net.Dns
Imports System.Net
Imports System.ComponentModel

Public Class Form1

    'Declare the variable for the computer we are going to ping
    Dim myComputer As String = "www.google.com"

    'Declare the background worker
    Dim worker As BackgroundWorker

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        'Without this the background ping would fail because the process is started in the GUI
        Control.CheckForIllegalCrossThreadCalls = False

        btnStop.Enabled = False

    End Sub

    Private Sub btnPing_Click(sender As Object, e As EventArgs) Handles btnPing.Click

        'starts the progress bar and continuously runs while the ping is running
        ProgressBar1.Enabled = True
        ProgressBar1.Style = ProgressBarStyle.Marquee
        btnPing.Enabled = False
        btnStop.Enabled = True
        'Run the ping in the background to keep the UI from freezing
        worker = New BackgroundWorker
        worker.WorkerSupportsCancellation = True
        worker.RunWorkerAsync()
        AddHandler worker.DoWork, AddressOf myWorker

    End Sub

    Private Sub btnStop_Click(sender As Object, e As EventArgs) Handles btnStop.Click
        ProgressBar1.Enabled = False
        worker.CancelAsync()
    End Sub

    Private Sub reportsuccess()

        rtbPingResults.AppendText("Ping Successful" & vbTab & myComputer.ToString & vbTab & IPAddresses(myComputer) & vbTab & Now)
        rtbPingResults.AppendText(Environment.NewLine)
        rtbPingResults.AppendText(Environment.NewLine)

    End Sub

    Private Sub reportfailure()

        rtbPingResults.AppendText("Ping Failure" & vbTab & myComputer.ToString & vbTab & IPAddresses(myComputer) & vbTab & Now)
        rtbPingResults.AppendText(Environment.NewLine)
        rtbPingResults.AppendText(Environment.NewLine)

    End Sub
    Sub myWorker(sender As Object, e As DoWorkEventArgs) 'Ping
        Do

                Try
                    If My.Computer.Network.Ping(myComputer) Then
                        Me.Text = "Successfully Pinging '" & myComputer & "'"
                        rtbPingResults.BackColor = Color.Honeydew
                        reportsuccess()
                    Else
                        Me.Text = "Failing to Ping '" & myComputer & "'"
                        rtbPingResults.BackColor = Color.Firebrick
                        reportfailure()
                    End If

                Catch ex As Exception
                    MsgBox("An error has occurred")
                    rtbPingResults.BackColor = Color.Red
                End Try
                Thread.Sleep(2000)

        Loop

    End Sub

    Function IPAddresses(Optional ByVal HostName As String = "") As String 'Gets all the ip addresses associated to the FQDN
        Dim IPEntry As IPHostEntry

        Try
            If HostName = "" Then
                IPEntry = GetHostEntry(GetHostName)
            Else
                IPEntry = GetHostEntry(HostName)
            End If
        Catch
            Return ""
        End Try

        Dim X As Integer = 0
        Dim Buffer As String = ""

        For X = 0 To IPEntry.AddressList.Count - 1
            If IPEntry.AddressList(X).AddressFamily = Sockets.AddressFamily.InterNetwork Then
                If Buffer = "" Then
                    Buffer = IPEntry.AddressList(X).ToString
                Else
                    Buffer = Buffer & ", " & IPEntry.AddressList(X).ToString
                End If
            End If
        Next

        Return Buffer

    End Function

End Class

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
Set the WorkerSupportsCancellation to True, then call the CancelAsync method.
ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
On a second look, I see that you've already done that  : \

I take it that isn't working for you?
High School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
Top Expert 2009
Commented:
In the documentation linked by kaufmed:

    "The worker code should periodically check the CancellationPending property to see if it has been set to true."

You're not doing that.
ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
Haha...  overshadowed by the great IM. Always a pleasure  : D

Myself, I'm wondering why the call to Control.CheckForIllegalCrossThreadCalls = False. Seems a flaw in the design. A BW shouldn't need to do cross-thread calls, but I haven't studied the code in great depth either.
Mike TomlinsonHigh School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
Top Expert 2009

Commented:
He's still learning.  The code started out with just Timers and he's added BackgroundWorkers in an attempt to keep the UI responsive.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial