使用 AsyncAwait 执行线程安全调用

如果我们尝试从不同的线程更改 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

VB 14.0.NET 4.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

使用 VB 14.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