Home > Backend Development > C++ > How to Implement a Timeout for WebClient.DownloadFile()?

How to Implement a Timeout for WebClient.DownloadFile()?

Susan Sarandon
Release: 2025-01-11 17:57:42
Original
434 people have browsed it

How to Implement a Timeout for WebClient.DownloadFile()?

Implementing Timeouts for WebClient.DownloadFile()

To prevent indefinite delays when downloading files from potentially slow or unresponsive servers, implementing a timeout for WebClient.DownloadFile() is essential. This example demonstrates a custom solution:

We create a derived class, WebDownload, inheriting from the base WebClient class:

<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>
Copy after login

The Timeout property, set in milliseconds, controls the download timeout.

Usage is straightforward: instantiate the WebDownload class and use it like the standard WebClient:

<code class="language-csharp">using (WebDownload client = new WebDownload(10000)) // 10-second timeout
{
    client.DownloadFile("http://example.com/file.zip", "file.zip");
}</code>
Copy after login

This approach ensures that your download operation won't hang indefinitely if the file is inaccessible or the server is unresponsive, providing a robust solution for file downloads.

The above is the detailed content of How to Implement a Timeout for WebClient.DownloadFile()?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template