问题描述
当我尝试以下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()什么是错在我这里异步使用的方式?
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:
超时属性对异步请求没有影响。
我推荐你使用
的HttpClient
来代替,这是设计时考虑异步请求。
I recommend you use
HttpClient
instead, which was designed with asynchronous requests in mind.
这篇关于在HttpWebRequest.GetResponse()VS GetResponseAsync(超时行为)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!