Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Polly CircuitBreakerAsync没有像我预期的那样工作_C#_Async Await_Polly_Circuit Breaker - Fatal编程技术网

C# Polly CircuitBreakerAsync没有像我预期的那样工作

C# Polly CircuitBreakerAsync没有像我预期的那样工作,c#,async-await,polly,circuit-breaker,C#,Async Await,Polly,Circuit Breaker,我只是在试用Polly CircuitBreakerAsync,它并没有像我预期的那样工作 我做错了什么?我希望下面的代码完成,并说电路仍然关闭 using Polly; using System; using System.Threading.Tasks; public class Program { public static void Main(string[] args) { MainAsync(args).GetAwaiter().GetResult

我只是在试用Polly CircuitBreakerAsync,它并没有像我预期的那样工作

我做错了什么?我希望下面的代码完成,并说电路仍然关闭

using Polly; 
using System;
using System.Threading.Tasks;

public class Program
{
    public static void Main(string[] args)
    {
        MainAsync(args).GetAwaiter().GetResult();
    }
    
    static async Task MainAsync(string[] args)
    {
        var circuitBreaker = Policy
            .Handle<Exception>()
            .CircuitBreakerAsync(
                3, // ConsecutiveExceptionsAllowedBeforeBreaking,
                TimeSpan.FromSeconds(5) // DurationOfBreak
            );

        Console.WriteLine("Circuit state before execution: " + circuitBreaker.CircuitState);

        await circuitBreaker.ExecuteAsync(() => Task.Delay(25));
        await circuitBreaker.ExecuteAsync(() => Task.Delay(25));
        await circuitBreaker.ExecuteAsync(() => { throw new System.Exception(); });
        await circuitBreaker.ExecuteAsync(() => Task.Delay(25));
        await circuitBreaker.ExecuteAsync(() => Task.Delay(25));

        Console.WriteLine("Circuit state after execution: " + circuitBreaker.CircuitState);
    }
}
使用Polly;
使用制度;
使用System.Threading.Tasks;
公共课程
{
公共静态void Main(字符串[]args)
{
MainAsync(args).GetAwaiter().GetResult();
}
静态异步任务mainsync(字符串[]args)
{
无功断路器=策略
.Handle()
.CircuitBreakerAsync(
3、//中断前允许的连续异常,
TimeSpan.FromSeconds(5)//中断持续时间
);
Console.WriteLine(“执行前的电路状态:+断路器.CircuitState”);
等待断路器。执行同步(()=>任务。延迟(25));
等待断路器。执行同步(()=>任务。延迟(25));
等待断路器.ExecuteAsync(()=>{throw new System.Exception();});
等待断路器。执行同步(()=>任务。延迟(25));
等待断路器。执行同步(()=>任务。延迟(25));
Console.WriteLine(“执行后的电路状态:+断路器.CircuitState”);
}
}
小提琴:

输出:

Circuit state before execution: Closed
Run-time exception (line 25): Exception of type 'System.Exception' was thrown.

Stack Trace:

[System.Exception: Exception of type 'System.Exception' was thrown.]
   at Program.<MainAsync>b__2() :line 25
   at Polly.Policy.<>c__DisplayClass116_0.<ExecuteAsync>b__0(Context ctx, CancellationToken ct)
   at Polly.CircuitBreakerSyntaxAsync.<>c__DisplayClass4_1.<<CircuitBreakerAsync>b__2>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Polly.CircuitBreaker.CircuitBreakerEngine.<ImplementationAsync>d__1`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Polly.Policy.<ExecuteAsync>d__135.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Program.<MainAsync>d__a.MoveNext() :line 25
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Program.Main(String[] args) :line 9
执行前的电路状态:关闭 运行时异常(第25行):引发了“System.exception”类型的异常。 堆栈跟踪: [System.Exception:引发了类型为'System.Exception'的异常。] 在程序.b__2()处:第25行 在Polly.Policy.c___显示Class116_0.b__0(上下文ctx,取消令牌ct) 在Polly.CircuitBreakerSyntaxAsync.c__DisplayClass4_1.d.MoveNext()中 ---来自引发异常的上一个位置的堆栈结束跟踪--- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务) 在System.Runtime.CompilerServices.TaskWaiter.HandleNonSuccessAndDebuggerNotification(任务任务)中 在Polly.断路器.断路器发动机.d_u1`1.移动下一个() ---来自引发异常的上一个位置的堆栈结束跟踪--- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务) 在System.Runtime.CompilerServices.TaskWaiter.HandleNonSuccessAndDebuggerNotification(任务任务)中 在Polly.Policy.d_u135.MoveNext()上 ---来自引发异常的上一个位置的堆栈结束跟踪--- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务) 在System.Runtime.CompilerServices.TaskWaiter.HandleNonSuccessAndDebuggerNotification(任务任务)中 在System.Runtime.CompilerServices.TaskAwaiter.GetResult()中 在Program.d_ua.MoveNext():第25行 ---来自引发异常的上一个位置的堆栈结束跟踪--- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务) 在System.Runtime.CompilerServices.TaskWaiter.HandleNonSuccessAndDebuggerNotification(任务任务)中 在System.Runtime.CompilerServices.TaskAwaiter.GetResult()中 在Program.Main(字符串[]args)处:第9行
这正按预期工作

异常处理

断路器作为测量和断开装置存在:用于 度量通过它放置的操作引发的已处理异常,以及 当超过配置的故障阈值时中断

  • 断路器不协调重试
  • 断路器不会(与重试不同)吸收异常通过策略执行的操作引发的所有异常(都是 本政策处理的例外情况(而非)是故意的 收回。策略更新度量所处理的异常 电路状态;未由策略处理的例外情况不适用
简而言之,它不会处理您的异常,它通常会重新触发它们

断路器 您的代码按预期工作。断路器本身不会断开,因为您已将连续错误计数设置为3。这意味着,如果连续3次调用失败,则它将从
Closed
状态转换为
Open
。如果您尝试执行另一个调用,那么它将抛出一个
brokencircuiitexception
。在
Closed
状态下,如果已引发异常且未达到阈值,则会重新引发异常

我总是建议把断路器当作代理。如果一切正常,它允许呼叫。如果消耗的子系统/子组件似乎出现故障,则它将阻止进一步调用以避免不必要的负载

用于调试的回调函数 定义断路器策略时,可以指定3个回调:

  • onBreak
    :当它从
    Closed
    half Open
    转换到
    Open
  • onReset
    :当它从
    half-open
    转换到
    Close
  • onHalfOpen
    :当它从
    Open
    转换到
    HalfOpen
经修订的政策声明:

var断路器=策略
.Handle()
.CircuitBreakerAsync(3,从秒开始的时间跨度(5),
onBreak:(ex,@break)=>Console.WriteLine($“{”break',-10}{@break,-10:ss\\.fff}:{ex.GetType().Name}”),
onReset:()=>Console.WriteLine($“{”Reset“,-10}”),
onHalfOpen:()=>Console.WriteLine($“{”HalfOpen“,-10}”)
);
连续故障计数 让我们将连续失败阈值更改为1,并将您的
ExecuteAsync
调用包装为try-catch:

var断路器=策略
.Handle()
.CircuitBreakerAsync(1,从秒开始的时间跨度(5),
onBreak:(ex,@break)=>Console.WriteLine($“{”break',-10}{@break,-10:ss\\.fff}:{ex.GetType().Name}”),
onReset:()=>Console.WriteLine($“{”Reset“,-10}”),
onHalfOpen:()=>Console.WriteLine($“{”HalfOpen“,-10}”)
);
Console.WriteLine(“执行前的电路状态:”+circuitBreaker.CircuitSta
Circuit state before execution: Closed
Break     05.000    : Exception
Circuit state after execution: Open
Exception
Circuit state before execution: Closed
Break     05.000    : Exception
Retry     01.000    : Exception
Circuit state after execution: Open
BrokenCircuitException
Circuit state before execution: Closed
Break     01.500    : Exception
Retry     01.000    : Exception
Retry     01.000    : BrokenCircuitException
HalfOpen
Break     01.500    : Exception
Circuit state after execution: Open
Exception