I want to show the random Quotes from zenquotes.io with the help of API.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Label4.Text = GetQuotes().ToString
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Public Async Function GetQuotes() As Task(Of String)
Using client = New HttpClient()
Dim response = Await client.GetAsync("https://zenquotes.io/api/random")
response.EnsureSuccessStatusCode()
Dim content As String = Await response.Content.ReadAsStringAsync()
Return content
End Using
End Function
However, this shows the text System.Threading.Tasks.Task``1[System.String]
in the label instead of a quote.
How can I fix it?
1
The GetQuotes()
function doesn’t directly return a string you can use to set the label. It’s an async function returning a Task
that can be converted to a string. What you are seeing is the result of calling the ToString()
method on this Task object. You have to await
or otherwise process that Task before you can get the string you want.
Ideally, I’d use the Await
option, but that would require you to also mark the event handler method as Async
, and I don’t have a lot of practice yet doing that for WinForms events. So instead I’ll suggest this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim t As Task(Of String) = GetQuotes()
t.GetAwaiter().GetResult()
Label4.Text = t.Result
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Again: this isn’t really how async operations are normally done, and maybe you should just mark the Button_Click method as Aysnc so you can await the task:
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Label4.Text = Await GetQuotes()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
But I don’t have personal experience doing it this way in Windows forms, for whether there might be odd side effects having an Async event handler on forms control.