我正在进行线程化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
答案 0 :(得分:1)
您将最后一个参数中的Object
传递给BeginGetRequestStream
。目前你有:
Dim result As IAsyncResult = CType(request.BeginGetRequestStream(AddressOf GetRequestStreamCallback, request), IAsyncResult)
您在result
参数中传递了state
,并且该值已在传递的AsyncState
的{{1}}属性中设置。
如果你想传递两个值,你有一些选择:
IAsyncResult
和result
值作为单独属性的新对象。index
数组,其中第一项是请求,第二项是索引。然后,您可以获取Object
属性,将其置于对象数组中,并剥离项目。AsyncState
参数中传递Tuple
。我更喜欢第二种,因为它很容易,但创建state
更清洁(即类型安全)并且几乎一样容易。我在https://stackoverflow.com/a/4555766/56778处有第二个方法的C#示例。