Imports System.Threading Public Class Form1 Private _TV As New TreeView With {.Dock = DockStyle.Fill} Private _LB As New ListBox With {.Dock = DockStyle.Fill} Private _cts As CancellationTokenSource Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load 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) Try SendKeys.SendWait("{ESC}") 'Await Task.Delay(1000) _cts = New CancellationTokenSource() Select Case e.Node.Text Case "1" Await Task.Run(Sub() Try For Each item In Enumerable.Range(1, 10000) _cts?.Token.ThrowIfCancellationRequested() SetText($"Node1({item})") Next Catch ex As OperationCanceledException Invoke(Sub() _LB.Items.Add("1 キャンセル ★★★★★★★★★★★★★★★★★★★★★★★★")) End Try End Sub) Case "2" Await Task.Run(Sub() Try For Each item In Enumerable.Range(1, 10000) _cts?.Token.ThrowIfCancellationRequested() SetText($"Node2({item})") Next Catch ex As OperationCanceledException Invoke(Sub() _LB.Items.Add("2 キャンセル ★★★★★★★★★★★★★★★★★★★★★★★★")) End Try End Sub) Case "ListBox Clear" _LB.Items.Clear() End Select Finally _cts?.Dispose() _cts = Nothing End Try 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