c# - 使用 HttpWebRequest.BeginGetResponse 超时的最佳方法

标签 c# asynchronous httpwebrequest timeout waithandle

HttpWebRequest.BeginGetResponse 不遵守 HttpWebRequest 的任何超时属性(Timeout 或 ReadWriteTimeout)。

我阅读了一些方法来获得相同的结果,但我不知道这是否是最好的方法,我是否应该使用少量调用或者我可以在循环内扩展它(我正在做一个网络爬虫)。

重要的是,最初我的代码不是异步的,我只需要异步,因为我的方法应该接受 CancellationToken。

我担心的是 WaitHandles 和 ThreadPool.RegisterWaitForSingleObject。这不是日常代码,所以我不知道在不久的将来是否会遇到问题。

private static void HandleCancellation(HttpWebRequest request, IAsyncResult getResponseResult, CancellationToken cancellationToken)
{
    using (WaitHandle requestHandle = getResponseResult.AsyncWaitHandle)
    {
        ThreadPool.RegisterWaitForSingleObject(requestHandle, TimeoutCallback, request, request.Timeout, true);

        //If request finish or cancellation is called
        WaitHandle.WaitAny(new[] {requestHandle, cancellationToken.WaitHandle});
    }

    //If cancellation was called
    if (cancellationToken.IsCancellationRequested)
    {
        request.Abort();
        cancellationToken.ThrowIfCancellationRequested();
    }
}

调用(同样,它不是异步的)

IAsyncResult getResponseResult = request.BeginGetResponse(null, null);

HandleCancellation(request, getResponseResult, cancellationToken);

return (HttpWebResponse)request.EndGetResponse(getResponseResult);

引用:Better approach in management of multiple WebRequest

最佳答案

BeginGetResponse 的 MSDN 文档有一个很好的例子来说明如何处理超时。它在我的网络爬虫中运行良好。

关于c# - 使用 HttpWebRequest.BeginGetResponse 超时的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10497853/

相关文章:

c# - 为什么扩展方法需要 "static"和 "this",它们的内存是如何分配的?

c# - 将跳入 Powerbuilder。任何建议

.net - 获取使用 HttpWebRequest/HttpWebResponse 发出的 HTTP 请求和响应以在 Fiddler 中显示

c# - 如何在 XP 和 7 之间使用不同的浏览器或 CredentialCache.DefaultCredentials 代理

jsf - 如何在@Asynchronous 方法中正确使用CDI?

dom - 不使用客户端 Javascript 的动态异步表单和网页可能吗?

c# - 使 AsyncLocal 更改传播到调用函数

c# - HttpWebRequest.GetRequestStream : What it does?

c# - 并行 http 请求

c# - 如何向 CMD 发送一个有多个零的字符串?