我试图异步获取HttpWebResponse对象,以便可以允许取消请求(使用BackgroundWorker.CancellationPending标志)。但是,下面的request.BeginGetResponse行会阻塞,直到返回响应为止(这可能需要一分钟以上的时间)。

Public Function myGetResponse(ByVal request As HttpWebRequest, ByRef caller As System.ComponentModel.BackgroundWorker) As HttpWebResponse
    'set a flag so that we can wait until our async getresponse finishes
    Dim waitFlag = New ManualResetEvent(False)

    Dim recieveException As Exception = Nothing

    Dim response As HttpWebResponse = Nothing
    'I use beginGetResponse here and then wait for the result, rather than just using getResponse
    'so that this can be aborted cleanly.
    request.BeginGetResponse(Sub(result As IAsyncResult)
                                 Try 'catch all exceptions here, so they can be raised on the outer thread
                                     response = request.EndGetResponse(result)
                                 Catch e As Exception
                                     recieveException = e
                                 End Try

                                 waitFlag.Set()
                             End Sub, Nothing)


    While Not waitFlag.WaitOne(100) AndAlso Not caller.CancellationPending
        'check for cancelation every 100ms
    End While


    'if our async read from the server returned an exception, raise it here.
    If recieveException IsNot Nothing Then
        Throw recieveException
    End If

    Return response
End Function


BeginGetResponseThe MSDN documentation包括以下段落:


在此方法变为异步之前,BeginGetResponse方法需要完成一些同步设置任务(例如DNS解析,代理检测和TCP套接字连接)。结果,永远不要在用户界面(UI)线程上调用此方法,因为它可能要花一些时间,通常是几秒钟。在某些Webproxy脚本配置不正确的环境中,这可能需要60秒或更长时间。配置文件元素上的downloadTime属性的默认值为一分钟,这占了大多数潜在的时间延迟。


我是在做错什么,还是这些最初的同步任务导致了延迟?如果是后者,如何使该调用实际上异步?

This answer似乎暗示可能是.NET错误,但是我知道我使用的URL有效(我在本地运行开发服务器)

我正在使用VS 2010和.NET 4.0

最佳答案

尽管这实际上只是黑暗中的一击,但我之前曾遇到过。

您没有显示如何配置HttpWebRequest对象。如果这是POST请求,则必须使用BeginGetRequestStream发送数据。正如HttpWebRequest.BeginGetResponse的文档所述:


您的应用程序不能为特定请求混合同步和异步方法。如果调用BeginGetRequestStream方法,则必须使用BeginGetResponse方法来检索响应。

08-06 04:30
查看更多