Hi
Here is one way of doing it. This example is JUST to show a generalize approach as I do noy have your data etc.
Setting up a simple BackGroundWorker to run your time consuming work. Allow the work to be interrupted and exit the BackGroundWorker using CancellationPending flag.
The example just uses a Thread.Sleep(2 seconds) in a generalized loop counting from 1 to 10.
Clicking the Start button starts the operation and the Stop button terminates the work.
In effect, putting your code into a BackGroundWorker and place the check for CancellationPending in an appropriate place (such as directly after the extract code for one item)
Example Form Design
Example Code
Option Strict On
Option Explicit On
Imports System.ComponentModel
Public Class Form1
Dim WithEvents bgw As New BackgroundWorker
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
bgw.WorkerSupportsCancellation = True
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'start operation
bgw.RunWorkerAsync()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'stop operation
bgw.CancelAsync()
End Sub
Private Sub bgw_DoWork(sender As Object, e As DoWorkEventArgs) Handles bgw.DoWork
Invoke(Sub() Label1.Text = "Running")
Invoke(Sub() Label2.Text = Nothing)
For Each entry As Integer In {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
'show loop counter in Label2
Invoke(Sub() Label2.Text = entry.ToString)
'emulate your operation with
' a dummy 'pause'
Threading.Thread.Sleep(2000)
'check for exit
If bgw.CancellationPending Then
Exit For
End If
Next
End Sub
Private Sub bgw_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles bgw.RunWorkerCompleted
Label1.Text = "Stopped"
End Sub
End Class