Maxime Visconte Maxime Visconte - 1 year ago 77 Question

Return values from asynchronous function

I'm trying to use my first Asynchronous function is VB.NET, and I get an error I don't understand.

I have read in the documentation ( that

' - The return type is Task or Task(Of T). (See "Return Types" section.)

' Here, it is Task(Of Integer) because the return statement returns an integer.

Here is the (very simple) code.

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

I have a compile error in the
funcAsync = result
line: Value of type 'Integer' cannot be converted to 'Task(Of Integer)'

I can't figure out what I did wrong here.

Thanks a lot for your help,

Answer Source

You can only use Await on functions declared with the "Async" keyword. And the "Async" keyword can't be used on a Sub.

If your code is for a Console Application, you need to put all your async processing inside of a function and on Sub Main you should call the Wait() method on the object returned by that function. Here is a code that works for me:

Sub Main()
End Sub

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

Async Function funcAsync() As Task(Of Integer)
    Dim result = 2
    Return result
End Function
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download