【问题标题】:Lazy timeout resolution Circuit Breaker is throwing ArgumentOutOfRangeException延迟超时解决断路器正在抛出 ArgumentOutOfRangeException
【发布时间】:2011-01-03 20:28:02
【问题描述】:

Ayende 将 a modification 发布到 Davy Brion 的 circuit breaker,其中他将超时分辨率更改为惰性模型。

private readonly DateTime expiry;

public OpenState(CircuitBreaker outer)
    : base(outer)
{
    expiry = DateTime.UtcNow + outer.timeout;
}

public override void ProtectedCodeIsAboutToBeCalled()
{
    if(DateTime.UtcNow < expiry)
        throw new OpenCircuitException();

    outer.MoveToHalfOpenState();
}

但是,构造函数可能会失败,因为TimeSpan 会很快溢出DateTime 的最大值。例如,当断路器的超时时间是 TimeSpan 的最大值时。

System.ArgumentOutOfRangeException 被捕获

Message="添加或减去的值导致无法表示的日期时间。"

...

在 System.DateTime.op_Addition(DateTime d, TimeSpan t)

我们如何避免这个问题并保持预期的行为?

【问题讨论】:

    标签: c# exception-handling timespan circuit-breaker


    【解决方案1】:

    做一点数学题

    确定超时是否大于DateTime 的最大值与当前DateTime 的余数。最大值TimeSpan 通常表示功能无限超时(使其成为“一次性”断路器)。

    public OpenState(CircuitBreaker outer)
        : base(outer)
    {
        DateTime now = DateTime.UtcNow;
        expiry = outer.Timeout > (DateTime.MaxValue - now) 
            ? DateTime.MaxValue
            : now + outer.Timeout;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多