/ Published in: C#
Simple implementation of a circuit breaker. Not threadsafe.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
class Program { static void Main() { while (true) { circuitBreaker.Invoke( x => x.GetTime(), time => Console.WriteLine(time), () => Console.WriteLine("Fast failing and not waiting for the service")); } } class UnreliableService { public DateTime GetTime() { if (Random.Next(10) == 1) { Console.WriteLine("UnreliableService is unreliable"); Thread.Sleep(1000); } return DateTime.Now; } } } class CircuitBreaker<T> { private readonly T _subject; private readonly int _resetTimeoutInMilliseconds; private DateTime? _errorTime; public CircuitBreaker(T subject, int resetTimeoutInMilliseconds) { _subject = subject; _resetTimeoutInMilliseconds = resetTimeoutInMilliseconds; _errorTime = null; } public void Invoke<TResult>(Func<T, TResult> func, Action<TResult> successAction, Action failAction) { if (_errorTime.HasValue) { if ((DateTime.Now - _errorTime.Value).TotalMilliseconds < _resetTimeoutInMilliseconds) { failAction.Invoke(); } } try { var result = func.Invoke(_subject); _errorTime = null; successAction.Invoke(result); } catch (Exception) { _errorTime = DateTime.Now; failAction.Invoke(); } } }