문제

사용 중입니다 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.OpenRead (...) 메소드를 사용 하여이 동기식으로 수행하고 싶다고 가정하고 리턴하는 스트림에서 타임 아웃을 설정합니다. 원하는 결과가 제공됩니다.

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

@beniamin이 제안한 타임 아웃을 설정하기 위해 WebClient에서 파생되고 GetWebrequest (...)를 우선적으로 수행하는 것은 저에게 효과가 없었지만 이렇게했습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top