tsk = AsyncMethod vs tsk = Task.Run(AddressOf AsyncMethod)线程的行为差异

时间:2014-10-14 00:57:47

标签: vb.net multithreading task-parallel-library async-await task

我正在尝试理解被称为“案例1”和“案例2”的2行代码的行为差异。 这是代码:

'Handler-----------------------------------------------------------------

Private Async Sub Button_Click(sender As Object, e As RoutedEventArgs)
        Await Worker()
End Sub

'Worker------------------------------------------------------------------

Async Function Worker() As Task
    Debug.WriteLine("I am worker just started. Thread is: " & System.Threading.Thread.CurrentThread.ManagedThreadId)

    'Dim tsk = Task.Run(AddressOf AsyncWork)       'Case 1
    Dim tsk = AsyncWork()                          'Case 2

    Dim b
    For j = 0 To 1000
        For i = 0 To 1000
            If i = 500 And j = 500 Then Debug.WriteLine("I am worker inside my circle. Thread is: " & System.Threading.Thread.CurrentThread.ManagedThreadId)
            b = i * j
        Next
    Next

    Await tsk.ConfigureAwait(False)

    Debug.WriteLine("I am worker after work. Thread is: " & System.Threading.Thread.CurrentThread.ManagedThreadId)

End Function

'Work------------------------------------------------------------------

Async Function AsyncWork() As Task(Of String)
    Await Task.Delay(1)
    Debug.WriteLine("I am work. Thread is: " & System.Threading.Thread.CurrentThread.ManagedThreadId)
    Dim a
    For j = 0 To 1000
        For i = 0 To 1000
            a = i * j
        Next
    Next
    Return a.ToString
End Function

在“案例1”中Dim tsk = Task.Run(AddressOf AsyncWork) AsyncWork方法按预期在单独的线程上启动。

我无法理解为什么在“案例2”中,当我键入Dim tsk = AsyncWork()时,AsyncWork方法开始在同一个线程上执行?这两行代码有什么区别?

enter image description here

1 个答案:

答案 0 :(得分:2)

在案例2中,您只是按照传统方式调用该函数。当然它会在同一个线程上运行 - 你没有要求任何不同的行为。

Task.Run()实际上是一个新任务,它最有可能发生在另一个线程上。