HttpRequest.BeginWebRequest not executing asynchronously

Posted by Shawn Simon on Stack Overflow See other posts from Stack Overflow or by Shawn Simon
Published on 2010-04-22T21:02:04Z Indexed on 2010/04/22 21:03 UTC
Read the original article Hit count: 576

Filed under:
|
|
|
|

I have the following code:

  Private Function CreateRequest() As HttpWebRequest
        Dim request As HttpWebRequest = HttpWebRequest.Create(_url)
        request.Method = "POST"
        request.ContentType = "application/x-www-form-urlencoded"
        Dim postData As String = String.Join("&", GetPostData().Select(Function(s) String.Format("{0}={1}", s.Key, HttpUtility.UrlEncode(s.Value))).ToArray)
        Dim data As Byte() = (New ASCIIEncoding).GetBytes(postData)
        request.Timeout = _maxTimeoutSeconds * 1000
        Dim stream = request.GetRequestStream
        stream.Write(data, 0, data.Length)
        stream.Close()
        Return request
    End Function

    Public Sub SendAsync(ByVal callback As Action(Of ResponseBase))
        Dim request = CreateRequest()
        _attemptCount += 1
        Dim reqID As Integer
        If _loggingContext IsNot Nothing Then
            Try
                reqID = Log.NotesRequest(_url.ToString, GetPostData, _loggingContext)
            Catch ex As Exception
                ErrorTracker.LogError(ex)
            End Try
        End If
        Dim responseState As New ResponseState
        responseState.LoggedNotesRequestID = reqID
        responseState.Request = request
        responseState.Callback = callback
        Dim response = request.BeginGetResponse(New AsyncCallback(AddressOf RespCallback), responseState)         
    End Sub

    Private Sub RespCallback(ByVal ar As IAsyncResult)
        Dim responseState As ResponseState = CType(ar.AsyncState, ResponseState)
        ' Process response...

I set up the request to go to a mock server which sleeps for 30 seconds. When I call BeginGetResponse, the application just waits at that line of code for the response. I want it to carry on with the app, and then just run the callback whenever it finishes. This code is run from a web page, and my callback just logs the response and sends an email. I don't want to use to have to wait for the response.

© Stack Overflow or respective owner

Related posts about ASP.NET

Related posts about c#