[英]In C# how to set timeout while using WebClient.DownloadStringTaskAsync method?
Now I am using HttpWebRequest.BeginGetResponse
method for http call, I want to migrate the code to async-await model.现在我使用
HttpWebRequest.BeginGetResponse
方法进行 http 调用,我想将代码迁移到 async-await 模型。 So, though of using WebClient.DownloadStringTaskAsync
method, but not sure how to set timeout?那么,虽然使用了
WebClient.DownloadStringTaskAsync
方法,但不确定如何设置超时?
The default timeout for WebClient
is 100 seconds (i believe) WebClient
的默认超时为 100 秒(我相信)
If you like you can CancelAsync()
with your own timeout, add pepper and salt to taste.如果您愿意,可以使用自己的超时
CancelAsync()
,加入胡椒和盐调味。
You use HttpWebRequest
rather than WebClient
(it uses the HttpWebRequest
internally).您使用
HttpWebRequest
而不是WebClient
(它在内部使用HttpWebRequest
)。 Using the HttpWebRequest
will allow you to set the timeout implicitly.使用
HttpWebRequest
将允许您隐式设置超时。
You could make a derived class which sets the timeout for the WebRequest
as seen from this answer您可以创建一个派生类来设置
WebRequest
的超时,如this answer所示
Set timeout for webClient.DownloadFile() 为 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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.