现在我正在使用HttpWebRequest.BeginGetResponse
方法进行http调用,我想将代码迁移到async-await模型。那么,虽然使用WebClient.DownloadStringTaskAsync
方法,但不确定如何设置超时?
WebClient
的默认超时是 100 秒(我相信(
-
如果您愿意,可以
CancelAsync()
自己的超时时间,加入胡椒粉和盐调味。 -
您可以使用
HttpWebRequest
而不是WebClient
(它在内部使用HttpWebRequest
(。使用该HttpWebRequest
将允许您隐式设置超时。 -
您可以创建一个派生类来设置
WebRequest
的超时,从这个答案可以看出
为 webClient.DownloadFile(( 设置超时
public class WebDownload : WebClient
{
/// <summary>
/// Time in milliseconds
/// </summary>
public int Timeout { get; set; }
public WebDownload() : this(60000) { }
public WebDownload(int timeout)
{
this.Timeout = timeout;
}
protected override WebRequest GetWebRequest(Uri address)
{
var request = base.GetWebRequest(address);
if (request != null)
{
request.Timeout = this.Timeout;
}
return request;
}
}