为什么异步函数返回 System.Threading.Tasks.Task`1[System.String]? [英] Why Async function returning System.Threading.Tasks.Task`1[System.String]?

查看:45
本文介绍了为什么异步函数返回 System.Threading.Tasks.Task`1[System.String]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 VB.NET 函数如下:

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

我正在尝试从数据库返回文档 ID,但我得到了

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

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

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

实际上它应该返回2"的地方.请帮我解决这个问题:这个功能我做错了什么?

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

更新

这里是调用的函数:

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

但是在文本框中我得到了上面的文本.谢谢.

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

推荐答案

我来自 C#,但工作方式应该相同.在较新的 .Net 版本 (>= 4.5) 中实现了 async/await.所以如果一个方法被标记为异步并返回一个任务(应该总是这样),你需要等待它.这意味着您也必须将您的方法标记为异步.所以你的电话应该是这样的:

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();

等待直到长时间运行的任务准备好并返回它的内部值.所有异步方法都应该返回任务.如果 Method 为 void,则为 Task.否则它可以是 Task 或任何其他类型.所以等待它,你可以继续运行;)

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 ;)

这篇关于为什么异步函数返回 System.Threading.Tasks.Task`1[System.String]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆