Link to home
Start Free TrialLog in
Avatar of Corey_Steinwand
Corey_Steinwand

asked on

How to stop a background worker vb.net

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

Avatar of kaufmed
kaufmed
Flag of United States of America image

Set the WorkerSupportsCancellation to True, then call the CancelAsync method.
On a second look, I see that you've already done that  : \

I take it that isn't working for you?
ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.
He's still learning.  The code started out with just Timers and he's added BackgroundWorkers in an attempt to keep the UI responsive.