vb.net HttpWebRequest BeginGetResponse参数

时间:2014-02-06 22:12:31

标签: multithreading parameters webrequest

我正在进行线程化webrequests。如何将参数'index'从Start()子句传递给GetResponseCallback()?

两个潜艇:

Shared Sub Start(ByVal index As Integer)
    Dim request As HttpWebRequest = CType(WebRequest.Create("http://sternbud.com/login/checklogin.php"), HttpWebRequest)

    request.ContentType = "application/x-www-form-urlencoded"
    request.Method = "POST"

    Debug.Print(index & ">" & AccountArray(dictThread.Keys(index)))

    Dim result As IAsyncResult = CType(request.BeginGetRequestStream(AddressOf GetRequestStreamCallback, request), IAsyncResult)

    allDone.WaitOne()
End Sub 

Private Shared Sub GetRequestStreamCallback(ByVal asynchronousResult As IAsyncResult)
    Dim request As HttpWebRequest = CType(asynchronousResult.AsyncState, HttpWebRequest)

    Dim postStream As Stream = request.EndGetRequestStream(asynchronousResult)
    Dim postData As [String] = "myusername=" & AccountArray(AccountIndex) & "&mypassword=test"


    Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)

    postStream.Write(byteArray, 0, postData.Length)
    postStream.Close()

    Dim result As IAsyncResult = CType(request.BeginGetResponse(AddressOf GetResponseCallback, request), IAsyncResult)
End Sub

1 个答案:

答案 0 :(得分:1)

您将最后一个参数中的Object传递给BeginGetRequestStream。目前你有:

Dim result As IAsyncResult = CType(request.BeginGetRequestStream(AddressOf GetRequestStreamCallback, request), IAsyncResult)

您在result参数中传递了state,并且该值已在传递的AsyncState的{​​{1}}属性中设置。

如果你想传递两个值,你有一些选择:

  1. 创建一个将IAsyncResultresult值作为单独属性的新对象。
  2. 创建一个index数组,其中第一项是请求,第二项是索引。然后,您可以获取Object属性,将其置于对象数组中,并剥离项目。
  3. 从您的两个值中创建Tuple,并在AsyncState参数中传递Tuple
  4. 我更喜欢第二种,因为它很容易,但创建state更清洁(即类型安全)并且几乎一样容易。我在https://stackoverflow.com/a/4555766/56778处有第二个方法的C#示例。