Hi,@Peter Volz. Welcome to Microsoft Q&A Forum.
To handle cancellation more effectively, you could use the CancellationToken and CancellationTokenSource classes, which provide a cooperative cancellation mechanism.
Here's an example of how you can use the CancellationTokenSource and CancellationToken for cooperative cancellation:
Imports System.Threading
Class MainWindow
Private cancellationTokenSource As CancellationTokenSource
Private Sub CancelButton_Click(sender As Object, e As EventArgs)
If cancellationTokenSource IsNot Nothing Then
cancellationTokenSource.Cancel()
End If
End Sub
Private Sub ThreadRoute()
Dim token As CancellationToken = cancellationTokenSource.Token
' For example:
While True
If token.IsCancellationRequested Then
' Clean up or save the current state before exiting
Exit While
End If
' Perform heavy work here
End While
End Sub
Private Sub StartThread()
cancellationTokenSource = New CancellationTokenSource()
Dim thread As New Thread(AddressOf ThreadRoute)
thread.Start()
End Sub
End Class
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.