如何在VB.NET中停止异步等待? [英] How do I stop async await in VB.NET?

查看:68
本文介绍了如何在VB.NET中停止异步等待?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在单击button1时调用的表单中有 async await 方法。当我点击button2时如何停止 async await



我尝试过的事情:



I have async await method in my form that I called when button1 is clicked. How do I stop the async await when I click button2?

What I have tried:

Private Async Sub Flash()
	While True
		Await Task.Delay(100)
		Label1.Visible = Not Label1.Visible
	End While
End Sub





以上代码是我的 Async Await 方法

推荐答案

使用取消关注源 [ ^ ]和取消提示 [ ^ ]:

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


这篇关于如何在VB.NET中停止异步等待?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆