gpt4 book ai didi

vb.net - HttpWebRequest.BeginGetResponse block ;异步获取 HttpWebResponse 的正确方法是什么?

转载 作者:行者123 更新时间:2023-12-02 06:41:51 25 4
gpt4 key购买 nike

我正在尝试异步获取 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

The MSDN documentation对于 BeginGetResponse 包含段落,

The BeginGetResponse method requires some synchronous setup tasks to complete (DNS resolution, proxy detection, and TCP socket connection, for example) before this method becomes asynchronous. As a result, this method should never be called on a user interface (UI) thread because it might take some time, typically several seconds. In some environments where the webproxy scripts are not configured properly, this can take 60 seconds or more. The default value for the downloadTime attribute on the config file element is one minute which accounts for most of the potential time delay.

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

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

我正在使用 VS 2010 和 .NET 4.0

最佳答案

我以前遇到过的事情可能就是这样,尽管这实际上只是在黑暗中刺伤。

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

Your application cannot mix synchronous and asynchronous methods for a particular request. If you call the BeginGetRequestStream method, you must use the BeginGetResponse method to retrieve the response.

关于vb.net - HttpWebRequest.BeginGetResponse block ;异步获取 HttpWebResponse 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22261820/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com