It can be challenging when using threading to have a thread that is working tell another thread that its mission is complete. Here is how I did it.
Imports System.Threading
‘ Create an event that the thread can raise to let the calling thread know it is complete
Public Event AccRunXrefCompletedHandler(ByVal sender As Object, ByVal e As EventArgs)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
‘ Add the event to this class
AddHandler AccRunXrefCompletedHandler, AddressOf AccRunXrefCompleted
End Sub
‘ Make this a class level variable so that you can keep a reference to the running thread
‘ this way if you want to terminate it you have the reference to do it with.
Dim processAccRunXref As Thread
‘ I am using this button click event to start the thread
Private Sub StartThreadProcess_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles StartThreadProcess.Click
‘ Create a new thread to run the process in
processAccRunXref = New Thread(AddressOf AccRunXref)
processAccRunXref.Start()
End Sub
Public Sub AccRunXref()
‘ Place your database code here
‘ This for loop is just to test with
For idx As Integer = 0 To 100000
Console.WriteLine(idx.ToString())
Next
‘ Raise the event to let the caller know we have completed
RaiseEvent AccRunXrefCompletedHandler(Me, EventArgs.Empty)
End Sub
Public Sub AccRunXrefCompleted(ByVal sender As Object, ByVal e As EventArgs)
‘ This event was raised by the thread to let us know it is done
‘ Do any processing here that needs to be don after the thread went to completion.
MessageBox.Show("Thread Completed")
processAccRunXref = Nothing
End Sub
‘ This button click event will abort the running thread if you need to stop it
Private Sub AbortThread_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AbortThread.Click
‘ If the thread is alive then abort it and reset the class variable to nothing
If processAccRunXref.IsAlive Then
processAccRunXref.Abort()
End If
processAccRunXref = Nothing
End Sub