在vb.net中“Await httpClient.GetAsync”不等待响应

问题描述 投票:0回答:1

我有以下代码

Public Class NfonService

  Public Async Function GetApiVersionAsync() As Task(Of Object)
     Debug.Print(0)
     Dim response As HttpResponseMessage = Await httpClient.GetAsync(BASE_URI & "/api/version")
     Debug.Print(1)
     Dim responseContent As String = Await response.Content.ReadAsStringAsync()
     Debug.Print("Result2:" & responseContent)
     Return responseContent
  End Function

End Class


Public Class Form1

  Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
     Dim MyNfonService As New NfonService
     Dim s As String
     Debug.Print("a")
     s = MyNfonService.GetApiVersionAsync().ToString
     Debug.Print("Result1:" & s)
     Debug.Print("b")
   End Sub

End Class

我希望调试输出按以下顺序

a
0
1
Result2: (some reasonable response text)
Result1: (same response text)
b

我正在

a
0
Result1: (nothing)
b
1
Result2: (some reasonable response text)

不应该

Dim response As HttpResponseMessage = Await httpClient.GetAsync(BASE_URI & "/api/version")
等待 httpClient.GetAsync 返回响应后再继续吗?我错过了什么?

vb.net async-await
1个回答
0
投票

在 GetAsync() 之后使用 .GetAwaiter().GetResult()

像这样

暗淡响应 As HttpResponseMessage = Await httpClient.GetAsync(BASE_URI & "/api/version").GetAwaiter().GetResult();

© www.soinside.com 2019 - 2024. All rights reserved.