Await / async - 异步方法在主线程中运行

时间:2014-01-24 07:48:51

标签: multithreading user-interface asynchronous task async-await

我刚开始学习Async / Await,我遇到了问题。有一个带有2个按钮的WinForms应用程序和永久运行状态栏。当按下第一个按钮 - 永远很好 - 在另一个线程中运行cicle并且UI不会冻结。当按下主线程中运行的第二个cicle时,UI会冻结。我只是无法得到它!为什么?对我来说,这种方法看起来几乎相同。顺便说一句,我的英语不好。

 Public Class Form1
    'Async - Create Task from Sync Method
    Private Async Sub btn_async_from_sync_Click(sender As Object, e As EventArgs) Handles btn_async_from_sync.Click
        Dim tsk As New Task(Of Integer)(AddressOf func_for_task)
        tsk.Start()
        Dim val As Integer = Await tsk
        MsgBox(val)
    End Sub
    Private Function func_for_task() As Integer
        Dim val As Integer
        For i = 1 To 999999999
            val += 1
        Next
        Return val
    End Function
    'Async - Use existing Task - Async Method
    Private Async Sub btn_async_use_task_Click(sender As Object, e As EventArgs) Handles btn_async_use_task.Click
        Dim tsk As Task(Of Integer) = func_for_task_async()
        Dim val As Integer = Await tsk
        MsgBox(val)
    End Sub
    Private Async Function func_for_task_async() As Task(Of Integer)
        Dim val As Integer
        For i = 1 To 999999999
            val += 1
        Next
        Return val
    End Function
End Class

1 个答案:

答案 0 :(得分:1)

不要忽略编译器警告。在这种情况下,编译器会警告您async方法不使用await,因此将同步运行。

在您的情况下,您可以使用Task.Run在后​​台线程上执行func_for_task,并在点击事件处理程序中使用await

有关详细信息,请参阅async/await intro on my blog