How to wait for an Async Call

RogerSchlueter-7899 1,526 Reputation points
2020-08-21T18:58:01.527+00:00

I get elevations for a set of map locations by:

Private Async Sub ProcessElementsAsync()
Await GetElevationsAsync()
....
End Sub

where:

Private Async Function GetElevationsAsync() As System.Threading.Tasks.Task
   Dim Reply As Response = Await   ServiceManager.GetResponseAsync(Request).ConfigureAwait(False)
 .....
End Sub

I can't proceed until GetElevationsAsync() completes yet the await operator does not seem to be working as I understand it. The processing does not wait for GetElevationsAsync() to finish so none of the requested elevations are available. How can I wait for GetElevationsAsync() to finish before proceeding to the rest of the code ?

Developer technologies | Windows Presentation Foundation
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Peter Fleischer (former MVP) 19,341 Reputation points
    2020-08-22T06:26:33.27+00:00

    Hi Roger,
    if a method is declared with the keyword async, an additional area is reserved in the stack. An instruction with await is started, the return information (CPU register, ...) for further work after the await is also stored in the stack (async area) and the control is returned to the caller without the further commands be processed after the await. Only when the waiting (await) has ended will the remaining commands of the method be processed after the await. The area in the stack created with async is used so that the runtime environment knows where to continue working in the interrupted method.

    When executing with await on a task that executes a Sub (method with no return value) asynchronously, execution are not waited. When await is executed with a task that asynchronously processes a Function (method with return value), await waits for the result.

    Try following demo:

    19632-x.png

    And CodeBehind:

    19633-x.png

    Result:

    19702-x.png

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.