locked
how stop thread vb.net RRS feed

  • Question

  •   Dim thr As New System.Threading.Thread(AddressOf up)
            thr.Start()


    Tuesday, October 13, 2015 2:28 AM

Answers

  • The code running would be in "uP" which you don't display.

    I suspect you have a loop of some type running in "up".

    You can try the Thread.Abort Method or the Thread.Abort Method (Object) to attempt to abort the thread. If a loop is running you can set a global boolean to false prior to launching the thread and in the loop if the boolean is true exit the loop and the sub using appropriate code and then try aborting the thread (although it may already have exited at that point). I would use a try/catch for aborting the thread in case the thread has exited so no error occurs trying to abort an exited thread.

    Plus globally I would use

    Dim thr As System.Threading.Thread

    then use the below in some event like a button click to instantiate a new thread and start it.

    thr = New System.Threading.Thread(AddressOf up)

    thr.Start()

    Option Strict On
    
    Public Class Form1
    
        Dim Thread1 As System.Threading.Thread
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Me.Location = New Point(CInt((Screen.PrimaryScreen.WorkingArea.Width / 2) - (Me.Width / 2)), CInt((Screen.PrimaryScreen.WorkingArea.Height / 2) - (Me.Height / 2)))
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Button1.Enabled = False
            StopThread = False
            Thread1 = New System.Threading.Thread(AddressOf ThreadNumber1)
            Thread1.Start()
        End Sub
    
        Dim StopThread As Boolean = False
        Dim Counter As Integer = 0
    
        Private Sub ThreadNumber1()
            For i = 0 To 100000000
                Counter = i
                Invoke(New Thread1AssistDelegate(AddressOf Thread1Assist))
                If StopThread = True Then
                    Exit Sub
                End If
            Next
        End Sub
    
        Private Delegate Sub Thread1AssistDelegate()
    
        Private Sub Thread1Assist()
            Label1.Text = Counter.ToString
        End Sub
    
        Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
            StopThread = True
            Button1.Enabled = True
            Try
                Thread1.Abort()
            Catch ex As Exception
            End Try
        End Sub
    
    End Class


    La vida loca

    Tuesday, October 13, 2015 2:48 AM