我正在使用 webClient.DownloadFile()来下载文件我可以为此设置超时,这样如果无法访问该文件就不会花这么长时间吗?

有帮助吗?

解决方案

尝试 WebClient.DownloadFileAsync()。您可以通过计时器使用自己的超时调用 CancelAsync()

其他提示

我的答案来自此处

您可以创建一个派生类,它将设置基本 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;
    }
}

并且您可以像使用基础WebClient类一样使用它。

假设您想要同步执行此操作,使用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);
               }
          }
     }
}

从WebClient派生并重写GetWebRequest(...)以设置建议的超时@Beniamin,对我来说不起作用,但是这样做了。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top