简体   繁体   English

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

[英]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.

相关问题 VS11中的WebClient.DownloadStringTaskAsync(Uri,CancellationToken)在哪里 - Where is WebClient.DownloadStringTaskAsync(Uri,CancellationToken) in VS11 WebClient.DownloadStringTaskAsync不等待就无法工作 - WebClient.DownloadStringTaskAsync doesn't work without await 等待WebClient.DownloadStringTaskAsync永远等待,但访问Result属性工作 - await WebClient.DownloadStringTaskAsync waits forever but accessing Result property works 如何停止多个webclient DownloadStringTaskAsync - How to stop multiple webclient DownloadStringTaskAsync 为什么WebClient.DownloadStringTaskAsync()会阻塞? - 新的异步API /语法/ CTP - Why does WebClient.DownloadStringTaskAsync() block ? - new async API/syntax/CTP C#DownloadStringTaskAsync:为什么未触发超时异常捕获? - C# DownloadStringTaskAsync: Why is the timeout exception catch not triggered? 如何在C#中使用WebClient触发事件处理程序并支持timeout属性来下载文件? - How can I download a file using WebClient in C# with firing the eventhandlers and supporting the timeout property? 如何在.net上为WebClient设置TimeOut? - How to Set TimeOut for WebClient on .net? 使用WebClient c# - Using WebClient c# 如何在 C# 中设置超时 - How to set timeout in C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM