在 C# 中,如何在使用 WebClient.DownloadStringTaskAsync 方法时设置超时?



现在我正在使用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;
}
}

相关内容

最新更新