我是 ASP.net (VB) 的绝对初学者。如果问题对于有经验的成员来说太明显了,请原谅我。
我尝试在异步模式下创建一个简单的 WebRequest,以防目标 URL 需要很长时间才能提供数据。在下面的代码中,我只想查看是否每次都正确调用了回调块(RespCallback)。如果一切顺利,每次我单击调用“GetData”子的按钮时,lblResult 都应该附加字符串“123”。
但是,第一次单击后 lblResult 仅显示 123。在随后的单击之后,lblResult 只附加了“12”,就好像永远不会调用 RespCallback。当我尝试在 Visual Studio 中对此进行调试时,执行实际上直接进入了 RespCallback 部分,并且 lblResult.Text 手表实际上显示了“123123”,但生成的网页始终只显示“12312”
我确定我在这里遗漏了一些基本的东西,但我只是不知道是什么。我什至猜测它与浏览器缓存有关(因此结果第二次发生变化),但我也不知道如何解决这个问题。
有人可以帮忙吗?提前致谢。
吉姆
Dim myWebRequest As WebRequest
Public Shared allDone As New ManualResetEvent(False)
Private Shared BUFFER_SIZE As Integer = 1024
Public Class RequestState
' This class stores the state of the request
Private Shared BUFFER_SIZE As Integer = 1024
Public requestData As StringBuilder
Public bufferRead() As Byte
Public request As WebRequest
Public response As WebResponse
Public responseStream As Stream
Public Sub New()
bufferRead = New Byte(BUFFER_SIZE) {}
requestData = New StringBuilder("")
request = Nothing
responseStream = Nothing
End Sub ' New
End Class ' RequestState
Public Sub GetData(Sender As Object, Args As System.EventArgs)
lblResult.Text += "1"
myWebRequest = WebRequest.Create(dataURL)
Dim myRequestState As New RequestState()
myRequestState.request = myWebRequest
' Start the asynchronous request.
Dim asyncResult As IAsyncResult = CType(myWebRequest.BeginGetResponse(AddressOf RespCallback, myRequestState), IAsyncResult)
lblResult.Text += "2"
allDone.WaitOne()
End Sub
Private Sub RespCallback(asynchronousResult As IAsyncResult)
lblResult.Text += "3"
allDone.Set()
End Sub