使用lambda表达式从Task获取值

时间:2017-10-30 11:21:38

标签: vb.net lambda async-await task

我写了一个简单的代码,其中POST凭证到一个网站。我需要返回值,但是我得到一个null,结果为ArgumentException。我该怎么做呢

Imports System.Net
Imports System.Text

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim routerUri = "http://127.0.0.1/login.cgi"
        Dim routerMethod = "POST"
        Dim routerPostData = New Specialized.NameValueCollection From {
                {"username", ""},
                {"password", ""},
                {"foo", "bar"}
            }
        Console.WriteLine(Encoding.UTF8.GetString(GetResponse(routerUri, routerMethod, routerPostData)))
    End Sub
    Function GetResponse(hUri As String, hMethod As String, rqParam As Specialized.NameValueCollection)
        Dim uriUri As New Uri(hUri)
        Dim rByte
        Dim tTask = New Task(
            Async Sub()
                Dim task As Task(Of Byte()) = SendRequest(uriUri, hMethod, rqParam)
                rByte = Await task
            End Sub)
        tTask.Start()
        tTask.Wait()
        Return rByte
    End Function

    Async Function SendRequest(hUri As Uri, hMethod As String, rqParam As Specialized.NameValueCollection) As Task(Of Byte())
        Dim rByte As Byte()
        Using client As New WebClient
            rByte = Await client.UploadValuesTaskAsync(hUri, hMethod, rqParam)
        End Using
        Return rByte
    End Function
End Class

1 个答案:

答案 0 :(得分:1)

事件处理程序允许Async Subs,因此最好只使处理程序异步并直接调用异步函数。避免手动创建新的Task

Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim routerUri = "http://127.0.0.1/login.cgi"
    Dim routerMethod = "POST"
    Dim routerPostData = New Specialized.NameValueCollection From {
            {"username", ""},
            {"password", ""},
            {"foo", "bar"}
        }
    Dim bytes = Await GetResponseAsync(routerUri, routerMethod, routerPostData)
    Console.WriteLine(Encoding.UTF8.GetString(bytes))
End Sub

GetResponseAsync

的位置
Async Function GetResponseAsync(hUri As String, hMethod As String, rqParam As Specialized.NameValueCollection) As Task(Of Byte())
    Dim uriUri As New Uri(hUri)
    Return Await SendRequest(uriUri, hMethod, rqParam)        
End Function

参考Async/Await - Best Practices in Asynchronous Programming