使用 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