Return to Snippet

Revision: 22723
at January 20, 2010 08:41 by jmcd


Initial Code
class Program
{
    static void Main()
    {
        var service = new UnreliableService();
        var circuitBreaker = new CircuitBreaker<UnreliableService>(service, 1000);

        while (true)
        {
            circuitBreaker.Invoke(
                x => x.GetTime(),
                time => Console.WriteLine(time),
                () => Console.WriteLine("Fast failing and not waiting for the service"));
        }
    }

    class UnreliableService
    {
        static readonly Random Random = new Random();
        public DateTime GetTime()
        {
            if (Random.Next(10) == 1)
            {
                Console.WriteLine("UnreliableService is unreliable");
                Thread.Sleep(1000);
                throw new TimeoutException();
            }
            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();
        }
    }
}

Initial URL

                                

Initial Description
Simple implementation of a circuit breaker.  Not threadsafe.

Initial Title
Simple Circuit Breaker in C#

Initial Tags

                                

Initial Language
C#