Use a
CancellationTokenSource[
^] and a
CancellationToken[
^]:
Private _cts As CancellationTokenSource
Private Async Function Flash(ByVal token As CancellationToken) As Task
While Not token.IsCancellationRequested
Await Task.Delay(100, token)
Label1.Visible = Not Label1.Visible
End While
End Function
Private Async Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim newSource As New CancellationTokenSource()
Dim oldSource As CancellationTokenSource = Interlocked.Exchange(_cts, newSource)
If oldSource IsNot Nothing Then oldSource.Cancel()
button1.Enabled = False
button2.Enabled = True
Try
Await Flash(newSource.Token)
Finally
Interlocked.Exchange(_cts, Nothing)
button2.Enabled = False
button1.Enabled = True
End Try
End Sub
Private Sub button2_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim cts As CancellationTokenSource = Interlocked.Exchange(_cts, Nothing)
If cts IsNot Nothing Then cts.Cancel()
End Sub