Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

vb.net - Why Async function returning System.Threading.Tasks.Task`1[System.String]?

I have a VB.NET function as below:

Public Shared Async Function GetIdDoc() As Task(Of String)
    Dim result As String = ""
    'Dim Uri As String = "http://localhost:53917/api/Documenti/GetNextIdDocumenti"
    Dim Uri As String = apiUri & ApiEndPoints.GetNextIdDocumenti

    Using client = New HttpClient()
        Using response = Await client.GetAsync(Uri)
            If response.IsSuccessStatusCode Then
                Dim DocumentiIDJsonString = Await response.Content.ReadAsStringAsync()
                result = DocumentiIDJsonString.ToString()

            End If
        End Using
    End Using
    Return result
End Function

I'm trying to return the Document ID from the DB but I'm getting

System.Threading.Tasks.Task`1[System.String]

Where actually it should return "2". Please help me on this: what am I doing wrong with this function?

Update

here is the function called:

 txtIDDoc_Detail.Text = ApiData.GetIdDoc().ToString()

But inside the textbox I'm getting the above text. thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm from C# but should work the same. In newer .Net Versions (>= 4.5) async/await is implemented. So if a method is marked as async and returns a Task (which should always be the case), you need to await it. This implicate that you have to mark your Method as async too. So your call should look like this:

txtIDDoc_Detail.Text = await ApiData.GetIdDoc();

The await waits till the long running Task is ready and returns it's inner value. All async Methods should return Task. If the Method is void it would be Task. Else it could be Task<int> or any other type. So await it and you can keep running ;)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...