2010-01-11 45 views
1

Ayende在Davy Brion的circuit breaker上發佈了a modification,其中他將超時分辨率更改爲懶惰模型。懶惰超時解析斷路器正在拋出ArgumentOutOfRangeException

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物「在未表示的日期時間的增加或減去值的結果。」抓住

消息=

...

在System.DateTime.op_Addition(日期時間d,時間跨度T)

我們如何避免這個問題,並保持預期的行爲?

回答

2

做數學

一點點

確定是否超時比一個DateTime和當前DateTime的最大值的剩餘更大。最大TimeSpan通常表示功能無限超時(使其成爲「一次性」斷路器)。

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