WebClient.DownloadFile()에 대한 시간 초과 구현
느리거나 응답하지 않는 서버에서 파일을 다운로드할 때 무기한 지연을 방지하려면 WebClient.DownloadFile()
에 대한 시간 초과를 구현하는 것이 필수적입니다. 이 예에서는 맞춤형 솔루션을 보여줍니다.
기본 WebDownload
클래스:WebClient
를 상속하여 파생 클래스
<code class="language-csharp">public class WebDownload : WebClient { /// <summary> /// Timeout in milliseconds /// </summary> public int Timeout { get; set; } public WebDownload() : this(60000) { } // Default 60-second timeout public WebDownload(int timeout) { this.Timeout = timeout; } protected override WebRequest GetWebRequest(Uri address) { WebRequest request = base.GetWebRequest(address); if (request != null) { request.Timeout = this.Timeout; } return request; } }</code>
밀리초 단위로 설정되는 Timeout
속성은 다운로드 시간 초과를 제어합니다.
사용법은 간단합니다. WebDownload
클래스를 인스턴스화하고 표준 WebClient
처럼 사용하세요.
<code class="language-csharp">using (WebDownload client = new WebDownload(10000)) // 10-second timeout { client.DownloadFile("http://example.com/file.zip", "file.zip"); }</code>
이 접근 방식은 파일에 액세스할 수 없거나 서버가 응답하지 않는 경우에도 다운로드 작업이 무기한 중단되지 않도록 하여 파일 다운로드를 위한 강력한 솔루션을 제공합니다.
위 내용은 WebClient.DownloadFile()에 대한 시간 초과를 구현하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!