温馨提示×

C# Polly怎样实现超时保护

c#
小樊
89
2024-07-13 23:41:22
栏目: 编程语言

在C#中使用Polly库实现超时保护非常简单。Polly是一个强大的库,可用于处理重试、断路器、超时等策略。

以下是一个示例代码,演示如何使用Polly库实现超时保护:

using Polly;
using System;
using System.Net.Http;

class Program
{
    static void Main()
    {
        Policy policy = Policy
            .Timeout(5, (context, timespan, task) =>
            {
                Console.WriteLine("请求超时");
            });

        HttpClient client = new HttpClient();

        // 发起一个带超时保护的请求
        policy.Execute(() =>
        {
            HttpResponseMessage response = client.GetAsync("http://www.example.com").Result;
            response.EnsureSuccessStatusCode();
            Console.WriteLine("请求成功");
        });
    }
}

在上面的示例中,我们创建了一个Policy对象,并指定了超时时间为5秒。然后,我们使用Execute方法来执行一个带有超时保护的HTTP请求。如果请求超时,则会触发超时策略中的处理逻辑。

通过使用Polly库,我们可以轻松地实现超时保护,确保我们的应用程序在处理外部服务调用时具有更高的可靠性和稳定性。

0