Home >Backend Development >C++ >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!