I'm doing threaded webrequests. How do I pass the parameter 'index' from the Start() sub to GetResponseCallback()?

The two subs:

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
有帮助吗?

解决方案

You pass it as an Object in the last parameter to BeginGetRequestStream. Currently you have:

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

You're passing the result in the state parameter, and that value gets set in the AsyncState property of the passed IAsyncResult.

If you want to pass two values, you have some choices:

  1. Create a new object that has the result and index values as separate properties.
  2. Create an array of Object where the first item is the request and the second is the index. You can then get the AsyncState property, case it to an object array, and peel out the items.
  3. Create a Tuple from your two values, and pass that Tuple in the state parameter.

I prefer the second because it's so easy, but creating a Tuple is cleaner (i.e. type-safe) and almost as easy. I have a C# example of the second method at https://stackoverflow.com/a/4555766/56778.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top