【问题标题】:In C# how to set timeout while using WebClient.DownloadStringTaskAsync method?在 C# 中如何在使用 WebClient.DownloadStringTaskAsync 方法时设置超时?
【发布时间】:2018-09-21 22:04:17
【问题描述】:

现在我使用HttpWebRequest.BeginGetResponse 方法进行http 调用,我想将代码迁移到async-await 模型。那么,虽然使用了WebClient.DownloadStringTaskAsync 方法,但不知道如何设置超时?

【问题讨论】:

标签: c# async-await webclient


【解决方案1】:

WebClient 的默认超时时间是 100 秒(我相信)

  • 如果您愿意,可以 CancelAsync() 自己暂停,加入胡椒和盐调味。

  • 您使用HttpWebRequest 而不是WebClient(它在内部使用HttpWebRequest)。使用HttpWebRequest 将允许您隐式设置超时。

  • 您可以创建一个派生类来设置WebRequest 的超时时间,从这个答案中可以看出

Set timeout for 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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-24
    • 1970-01-01
    • 1970-01-01
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 2020-07-12
    相关资源
    最近更新 更多