Imports System.Threading Public Class Form4 Private _TV As New TreeView With {.Dock = DockStyle.Fill} Private _LB As New ListBox With {.Dock = DockStyle.Fill} Private _cts As CancellationTokenSource Private Sub Form4_Shown(sender As Object, e As EventArgs) Handles Me.Shown Dim sp As New SplitContainer With {.Dock = DockStyle.Fill} Dim root As New TreeNode("Task Cancel") Dim tn1 As New TreeNode("1") Dim tn2 As New TreeNode("2") Dim tn3 As New TreeNode("ListBox Clear") root.Nodes.AddRange({tn1, tn2, tn3}) _TV.Nodes.Add(root) sp.Panel1.Controls.Add(_TV) sp.Panel2.Controls.Add(_LB) Controls.Add(sp) root.Expand() _TV.SelectedNode = root AddHandler _TV.AfterSelect, AddressOf TreeView_AfterSelect KeyPreview = True AddHandler Me.KeyDown, Sub(o, k) If k.KeyCode = Keys.Escape Then _cts?.Cancel() End If End Sub End Sub Private Async Sub TreeView_AfterSelect(sender As Object, e As TreeViewEventArgs) If _cts Is Nothing Then _cts = New CancellationTokenSource Else _cts.Cancel() Task.Delay(20).Wait() _cts = New CancellationTokenSource End If Select Case e.Node.Text Case "1" Await Task.Run(Sub() For Each item In Enumerable.Range(1, 10000) Task.Delay(1).Wait() If _cts.Token.IsCancellationRequested Then Invoke(Sub() _LB.Items.Add("1 キャンセル ★★★★★★★★★★★★★★★★★★★★★★★★")) Return End If SetText($"Node1({item})") Next End Sub, _cts.Token) Case "2" Await Task.Run(Sub() 'Try For Each item In Enumerable.Range(1, 10000) Task.Delay(1).Wait() If _cts.Token.IsCancellationRequested Then Invoke(Sub() _LB.Items.Add("2 キャンセル ★★★★★★★★★★★★★★★★★★★★★★★★")) Return End If SetText($"Node2({item})") Next End Sub, _cts.Token) Case "ListBox Clear" _LB.Items.Clear() End Select End Sub Private Sub SetText(s As String) If InvokeRequired Then Invoke(Sub() SetText(s)) Else _LB.Items.Add(s) End If End Sub End Class