异步函数的返回值

Max*_*ime 1 vb.net asynchronous

我尝试使用我的第一个异步函数是 VB.NET,但出现了一个我不明白的错误。

我在文档(https://msdn.microsoft.com/fr-fr/library/mt674902.aspx)中读到

' - 返回类型为 Task 或 Task(Of T)。(请参阅“返回类型”部分。)

' 这里,它是 Task(Of Integer),因为 return 语句返回一个整数。

这是(非常简单)代码。

Async Sub Main()
    Dim test
    test = Await funcAsync()
End Sub

Function funcAsync() As Task(Of Integer)
    Dim result As Integer
    result = 2
    funcAsync = result
End Function
Run Code Online (Sandbox Code Playgroud)

我在行中遇到编译错误funcAsync = result:“Integer”类型的值无法转换为“Task(Of Integer)”

我不明白我在这里做错了什么。

非常感谢你的帮助,

小智 5

您只能在使用“Async”关键字声明的函数上使用 Await。并且“Async”关键字不能在 Sub 上使用。

如果您的代码用于控制台应用程序,则需要将所有异步处理放在函数内,并且在 Sub Main 上,您应该对该函数返回的对象调用 Wait() 方法。这是一个适合我的代码:

Sub Main()
    DoProcessing().Wait()
    Console.ReadKey()
End Sub

Async Function DoProcessing() As Task
    Dim test = Await funcAsync()
    Console.WriteLine(test)
End Sub

Async Function funcAsync() As Task(Of Integer)
    Dim result = 2
    Return result
End Function
Run Code Online (Sandbox Code Playgroud)