0

I do something in a thread. But sometimes I don't want to wait till all pings are finished.

How can I cancel a thread?

Can you show me please the code?

Private Sub Start_Button_Click(sender As Object, e As EventArgs) Handles Start_Button.Click
    DoSomething()
End Sub
Private Sub Cancel_Button_Click(sender As Object, e As EventArgs) Handles Cancel_Button.Click
    THRD.Cancel '<-- Thread cancel!??!???
End Sub
Sub DoSomething()
    Dim THRD As New Thread(Sub()
                               Dim IPArea As String = "192.168.1."
                               Dim LastIP As Integer
                               For LastIP = 0 To 255
                                   Dim TestIP As String = IPArea & CStr(LastIP)
                                   If My.Computer.Network.Ping(TestIP, 10) Then
                                       ListBox1.Items.Add(TestIP)
                                   End If
                               Next
                           End Sub)
    THRD.IsBackground = True
    THRD.Start()
End Sub
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • This answer is a good read: https://stackoverflow.com/questions/3632149/question-about-terminating-a-thread-cleanly-in-net For starters you will need to change the scope of your `THRD` variable in order to call it from the button's click event. – Pete -S- Sep 05 '20 at 19:40
  • Exactly this what i don´t know how to do it and I can´t do anything with c#-code – vbnet_newer Sep 05 '20 at 20:50
  • Are you getting any type of other errors like Cross-thread operation not valid: Control 'ListBox1' accessed from a thread other than the thread it was created on.'? – Pete -S- Sep 05 '20 at 21:10
  • Only one error from the cancel_button because the code of THRD.Cancel is wrong. – vbnet_newer Sep 05 '20 at 21:17
  • Have you run this code without the `THRD.Cancel '<-- Thread cancel!??!???` in place? – Pete -S- Sep 05 '20 at 21:27
  • 2
    [Ping.SendAsync](https://learn.microsoft.com/en-us/dotnet/api/system.net.networkinformation.ping.sendasync) + [Ping.SendAsyncCancel](https://learn.microsoft.com/en-us/dotnet/api/system.net.networkinformation.ping.sendasynccancel). Ditch the thread. – Jimi Sep 05 '20 at 22:27

1 Answers1

1

Here is my working solution and this solution is only to show how to move the THRD as a form level variable to allow stopping it when clicking the cancel button. I added some validations to prevent exceptions.

Public Class Form1
    Private THRD As Threading.Thread

    Private Sub Start_Button_Click(sender As Object, e As EventArgs) Handles Start_Button.Click
        DoSomething()
    End Sub
    Private Sub Cancel_Button_Click(sender As Object, e As EventArgs) Handles Cancel_Button.Click

        If THRD IsNot Nothing AndAlso THRD.IsAlive Then
            THRD.Abort()  '<-- Thread cancel!??!???
            THRD = Nothing
            AddToList("Stopped.")
        Else
            AddToList("Thread not running.")
        End If
    End Sub

    Sub DoSomething()
        If THRD IsNot Nothing AndAlso THRD.IsAlive Then
            AddToList("Still working...")
            Exit Sub
        End If

        THRD = New Threading.Thread(Sub()
                                        Dim IPArea As String = "192.168.1."
                                        Dim LastIP As Integer
                                        For LastIP = 0 To 255
                                            Dim TestIP As String = IPArea & CStr(LastIP)
                                            If My.Computer.Network.Ping(TestIP, 10) Then
                                                AddToList(TestIP)
                                            End If
                                        Next
                                        AddToList("Done")
                                    End Sub)
        THRD.IsBackground = True
        THRD.Start()
    End Sub

    ''' <summary>
    ''' Thead-safe add value to list.
    ''' </summary>
    ''' <param name="value">The value.</param>
    Private Sub AddToList(value As String)
        If ListBox1.InvokeRequired Then
            ListBox1.Invoke(Sub() ListBox1.Items.Add(value))
        Else
            ListBox1.Items.Add(value)
        End If
    End Sub
End Class
Pete -S-
  • 542
  • 5
  • 13
  • One issue you have to address is if you cancel the thread, you may get this error: ThreadAbortException: Thread was being aborted. It may be better to use a delegate and put in a try/catch. – Pete -S- Sep 05 '20 at 21:46