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

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

Susan Sarandon
Susan SarandonOriginal
2025-01-11 17:41:41593browse

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

Efficiently manage WebClient.DownloadFile() timeouts

Setting a timeout for the WebClient.DownloadFile() method is critical to preventing long delays when files are downloaded. This article will explore an efficient solution to set a timeout for this operation.

We will create a derived class called WebDownload that inherits from the base class WebClient. The custom class will introduce the Timeout attribute, allowing us to set the desired timeout value.

Here is the C# code for the WebDownload class:

<code class="language-csharp">using System;
using System.Net;

public class WebDownload : WebClient
{
    public int Timeout { get; set; }

    public WebDownload() : this(60000) { }

    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>

By overriding the GetWebRequest method, we can intercept the WebRequest object and modify its Timeout properties based on the timeout value specified by the custom class. Now, when using the WebDownload class, you only need to provide the timeout duration in milliseconds during initialization.

For example:

<code class="language-csharp">WebDownload client = new WebDownload(30000); // 设置 30 秒超时
client.DownloadFile("http://example.com/file.zip", "file.zip");</code>

This will initiate a file download with a 30 second timeout. If the download cannot complete within this time frame, an exception is thrown, allowing you to handle the situation gracefully and avoid unnecessary delays.

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

Statement:
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