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

查看:1340
本文介绍了为什么异步函数返回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.因此,如果一个方法被标记为异步并返回一个Task(应该总是这样),则需要等待它.这意味着您也必须将Method标记为异步.因此您的通话应如下所示:

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

await等待直到长时间运行的Task准备好并返回其内部值.所有异步方法都应返回Task.如果该方法无效,则为任务".否则它可以是Task<int>或任何其他类型.因此,等待它,您就可以继续运行;)

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天全站免登陆