Simple Circuit Breaker in C#


/ Published in: C#
Save to your folder(s)

Simple implementation of a circuit breaker. Not threadsafe.


Copy this code and paste it in your HTML
  1. class Program
  2. {
  3. static void Main()
  4. {
  5. var service = new UnreliableService();
  6. var circuitBreaker = new CircuitBreaker<UnreliableService>(service, 1000);
  7.  
  8. while (true)
  9. {
  10. circuitBreaker.Invoke(
  11. x => x.GetTime(),
  12. time => Console.WriteLine(time),
  13. () => Console.WriteLine("Fast failing and not waiting for the service"));
  14. }
  15. }
  16.  
  17. class UnreliableService
  18. {
  19. static readonly Random Random = new Random();
  20. public DateTime GetTime()
  21. {
  22. if (Random.Next(10) == 1)
  23. {
  24. Console.WriteLine("UnreliableService is unreliable");
  25. Thread.Sleep(1000);
  26. throw new TimeoutException();
  27. }
  28. return DateTime.Now;
  29. }
  30. }
  31. }
  32.  
  33. class CircuitBreaker<T>
  34. {
  35. private readonly T _subject;
  36. private readonly int _resetTimeoutInMilliseconds;
  37. private DateTime? _errorTime;
  38.  
  39. public CircuitBreaker(T subject, int resetTimeoutInMilliseconds)
  40. {
  41. _subject = subject;
  42. _resetTimeoutInMilliseconds = resetTimeoutInMilliseconds;
  43. _errorTime = null;
  44. }
  45.  
  46. public void Invoke<TResult>(Func<T, TResult> func, Action<TResult> successAction, Action failAction)
  47. {
  48. if (_errorTime.HasValue)
  49. {
  50. if ((DateTime.Now - _errorTime.Value).TotalMilliseconds < _resetTimeoutInMilliseconds)
  51. {
  52. failAction.Invoke();
  53. }
  54. }
  55. try
  56. {
  57. var result = func.Invoke(_subject);
  58. _errorTime = null;
  59. successAction.Invoke(result);
  60. }
  61. catch (Exception)
  62. {
  63. _errorTime = DateTime.Now;
  64. failAction.Invoke();
  65. }
  66. }
  67. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.