Avatar of 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
        AddHandler worker.DoWork, AddressOf myWorker

    End Sub

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

    Private Sub reportsuccess()

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

    End Sub

    Private Sub reportfailure()

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

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

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

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


    End Sub

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

            If HostName = "" Then
                IPEntry = GetHostEntry(GetHostName)
                IPEntry = GetHostEntry(HostName)
            End If
            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
                    Buffer = Buffer & ", " & IPEntry.AddressList(X).ToString
                End If
            End If

        Return Buffer

    End Function

End Class

Open in new window

.NET ProgrammingVisual Basic.NET

Avatar of undefined
Last Comment
Mike Tomlinson

8/22/2022 - Mon

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?
Mike Tomlinson

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question

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.
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
Mike Tomlinson

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