Visual Basic .NET使用Async / Await执行线程安全的调用
示例
如果尝试从其他线程更改UI线程上的对象,则会得到跨线程操作异常:
Private Sub Button_Click(sender As Object, e As EventArgs) Handles MyButton.Click
' Cross thread-operation exception as the assignment is executed on a different thread
' from the UI one:
Task.Run(Sub()MyButton.Text= Thread.CurrentThread.ManagedThreadId)
End Sub在VB14.0和.NET4.5之前,该解决方案是在UI线程上调用赋值和对象:
Private Sub Button_Click(sender As Object, e As EventArgs) Handles MyButton.Click
' This will run the conde on the UI thread:
MyButton.Invoke(Sub()MyButton.Text= Thread.CurrentThread.ManagedThreadId)
End Sub在VB14.0中,我们可以Task在其他线程上运行,然后在执行完成后恢复上下文,然后使用Async/Await执行分配:
Private Async Sub Button_Click(sender As Object, e As EventArgs) Handles MyButton.Click
' This will run the code on a different thread then the context is restored
' so the assignment happens on the UI thread:
MyButton.Text= Await Task.Run(Function() Thread.CurrentThread.ManagedThreadId)
End Sub
热门推荐
4 带猫的祝福语简短
10 苦行老师祝福语结婚简短
11 春节福字祝福语简短
12 女友妈妈生日祝福语简短
13 送米的祝福语简短
14 节日结束祝福语简短的
15 送给妈妈新年祝福语简短
16 中秋给爸妈祝福语简短
17 病人的生日祝福语简短
18 经典座右铭简短祝福语英文