简体   繁体   English

为 webClient.DownloadFile() 设置超时

[英]Set timeout for webClient.DownloadFile()

I'm using webClient.DownloadFile() to download a file can I set a timeout for this so that it won't take so long if it can't access the file?我正在使用webClient.DownloadFile()下载文件,我可以为此设置超时,以便在无法访问该文件时不会花费这么长时间吗?

My answer comes from here 我的答案来自这里

You can make a derived class, which will set the timeout property of the base WebRequest class: 您可以创建派生类,它将设置基本WebRequest类的超时属性:

using System;
using System.Net;

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;
    }
}

and you can use it just like the base WebClient class. 你可以像基础WebClient类一样使用它。

Try WebClient.DownloadFileAsync() . 试试WebClient.DownloadFileAsync() You can call CancelAsync() by timer with your own timeout. 您可以使用自己的超时通过计时器调用CancelAsync()

Assuming you wanted to do this synchronously, using the WebClient.OpenRead(...) method and setting the timeout on the Stream that it returns will give you the desired result: 假设您想要同步执行此操作,使用WebClient.OpenRead(...)方法并在它返回的Stream上设置超时将为您提供所需的结果:

using (var webClient = new WebClient())
using (var stream = webClient.OpenRead(streamingUri))
{
     if (stream != null)
     {
          stream.ReadTimeout = Timeout.Infinite;
          using (var reader = new StreamReader(stream, Encoding.UTF8, false))
          {
               string line;
               while ((line = reader.ReadLine()) != null)
               {
                    if (line != String.Empty)
                    {
                        Console.WriteLine("Count {0}", count++);
                    }
                    Console.WriteLine(line);
               }
          }
     }
}

Deriving from WebClient and overriding GetWebRequest(...) to set the timeout @Beniamin suggested, didn't work for me as, but this did. 从WebClient派生并重写GetWebRequest(...)以设置建议的超时@Beniamin,对我来说不起作用,但是这样做了。

A lot of people make use of using(...) for the WebClient.很多人使用 using(...) 作为 WebClient。 Yes, WebClient implements IDisposable but this can cause socket exhaustion if you do it in bulk: https://www.as.netmonsters.com/2016/08/2016-08-27-httpclientwrong/是的,WebClient 实现了 IDisposable,但是如果你批量执行它会导致套接字耗尽: https://www.as.netmonsters.com/2016/08/2016-08-27-httpclientwrong/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM