Loading... # [Polly](https://github.com/App-vNext/Polly) 示例代码 ```csharp using System; using System.Net.Http; using Polly; class Program { static void Main() { // 创建一个HttpClient实例 HttpClient httpClient = new HttpClient(); // 定义重试策略 var retryPolicy = Policy .Handle<HttpRequestException>() // 指定需要重试的异常类型 .WaitAndRetry(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))); // 定义重试次数和重试间隔 // 使用重试策略发送请求 retryPolicy.Execute(() => { try { // 发送请求 HttpResponseMessage response = httpClient.GetAsync("https://api.example.com").Result; // 处理响应 if (response.IsSuccessStatusCode) { Console.WriteLine("请求成功!"); Console.WriteLine(response.Content.ReadAsStringAsync().Result); // 在此处可以对响应进行处理 } else { Console.WriteLine("请求失败!"); // 在此处可以对失败的情况进行处理 } } catch (Exception ex) { Console.WriteLine($"请求发生异常: {ex.Message}"); // 在此处可以对异常进行处理 } }); // 关闭HttpClient httpClient.Dispose(); } } ``` 最后修改:2023 年 06 月 22 日 © 允许规范转载 打赏 赞赏作者 微信 赞 0 如果觉得我的文章对你有用,请随意赞赏