在C#中,使用WebClient类时,可以通过设置HttpClientHandler的Timeout属性来为WebClient操作设置超时时间。以下是一个示例:
using System; using System.Net; using System.Net.Http; using System.Threading.Tasks; class Program { static async Task Main(string[] args) { // 创建一个HttpClientHandler实例 var handler = new HttpClientHandler(); // 设置连接超时时间(单位:毫秒) handler.ConnectTimeout = 5000; // 设置读取超时时间(单位:毫秒) handler.ReadTimeout = 5000; // 使用自定义的HttpClientHandler创建HttpClient实例 using (var httpClient = new HttpClient(handler)) { try { // 发起GET请求 var response = await httpClient.GetAsync("https://www.example.com"); // 读取响应内容 var content = await response.Content.ReadAsStringAsync(); // 输出响应内容 Console.WriteLine(content); } catch (HttpRequestException e) { // 处理请求异常 Console.WriteLine("Request error: " + e.Message); } } } } 在这个示例中,我们创建了一个HttpClientHandler实例,并分别设置了连接超时时间和读取超时时间。然后,我们使用这个handler创建了一个HttpClient实例,并发起了一个GET请求。如果请求在指定的超时时间内未完成,将会抛出HttpRequestException异常。