我有以下代码
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 返回响应后再继续吗?我错过了什么?
在 GetAsync() 之后使用 .GetAwaiter().GetResult()
像这样
暗淡响应 As HttpResponseMessage = Await httpClient.GetAsync(BASE_URI & "/api/version").GetAwaiter().GetResult();