OrElse
OrElse

Reputation: 9959

Value of type 'System.Threading.Tasks.Task(Of String)' cannot be converted to 'String'

I guess i am doing something terrible wrong here...

Dim s As String = GetResponse("", New KeyValuePair(Of String, String))

  Public Async Function GetResponse(ByVal url As String, ByVal params As KeyValuePair(Of String, String)) As System.Threading.Tasks.Task(Of String)
        Dim values = New List(Of KeyValuePair(Of String, String))
        Dim httpClient = New HttpClient(New HttpClientHandler())
        Dim response As HttpResponseMessage = Await httpClient.PostAsync(url, New FormUrlEncodedContent(values))
        response.EnsureSuccessStatusCode()
        Return Await response.Content.ReadAsStringAsync()
    End Function

any ideas please?

Upvotes: 1

Views: 5734

Answers (2)

Dominic B.
Dominic B.

Reputation: 1907

Your function returs not a string. it returns a Task(Of String), like it says in the error message and as you can see in your function declaration. You see, it is not working as you think.

Solution should be: Try calling GetResponse("", New KeyValuePair(Of String, String)).Result, that will do what you want. The Result is the type like the type parameter of your Task.

Upvotes: 4

Stephen Cleary
Stephen Cleary

Reputation: 456477

You should Await tasks to "unwrap" their result, as such:

Dim s As String = Await GetResponse("", New KeyValuePair(Of String, String))

Yes, this does mean that the calling method does need to be Async, so it's callers must use Await, etc. This is perfectly natural; Async does "infect" the code base like this.

Upvotes: 2

Related Questions