在HttpWebRequest.GetResponse()VS GetResponseAsync(超时行为) [英] Timeout behaviour in HttpWebRequest.GetResponse() vs GetResponseAsync()

查看:1930
本文介绍了在HttpWebRequest.GetResponse()VS GetResponseAsync(超时行为)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试以下code:

When I try the following code:

var request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Timeout = 3; // a small value

var response = request.GetResponse();
Console.WriteLine(response.ContentLength);

有关的URL,我知道这是要采取超过3毫秒加载(我放了 Thread.sleep代码(110000)的Application_BeginRequest ),它工作正常,并抛出一个引发WebException 预期。

for a URL that I know it is going to take more than 3 millisecond to load (I put a Thread.Sleep(110000) in Application_BeginRequest) it works fine and throws a WebException as expected.

问题是,当我切换到异步方法:

Problem is when I switch to async method:

var response = request.GetResponseAsync().Result;

var response = await request.GetResponseAsync();

这异步版本完全忽略任何超时值,包括 ReadWriteTimeout ServicePoint.MaxIdleTime

This async version completely ignores any Timeout value, including ReadWriteTimeout and ServicePoint.MaxIdleTime

我找不到关于超时MSDN的 GetResponseAsync()现在我想知道如果是在错误GetResponseAsync()<什么/ code>什么是错在我这里异步使用的方式?

I couldn't find anything about Timeout in MSDN's GetResponseAsync() now I'm wondering if it is a bug in GetResponseAsync() or something is wrong in the way I use async here?

推荐答案

超时不适用于异步的HttpWebRequest 要求。引用的文档

Timeout does not apply to asynchronous HttpWebRequest requests. To quote the docs:

超时属性对异步请求没有影响。

The Timeout property has no effect on asynchronous requests

我推荐你使用的HttpClient 来代替,这是设计时考虑异步请求。

I recommend you use HttpClient instead, which was designed with asynchronous requests in mind.

这篇关于在HttpWebRequest.GetResponse()VS GetResponseAsync(超时行为)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆