/src/LinFu.AOP.Interfaces/SingleThreadedCallCounter.cs

http://github.com/philiplaureano/LinFu · C# · 64 lines · 50 code · 13 blank · 1 comment · 4 complexity · 2b66b351d5df9a210e7b8939da662ebc MD5 · raw file

  1. using System.Collections.Generic;
  2. using System.Reflection;
  3. namespace LinFu.AOP.Interfaces
  4. {
  5. internal class SingleThreadedCallCounter : ICallCounter
  6. {
  7. private readonly Dictionary<object, Counter<MethodBase>>
  8. _counts = new Dictionary<object, Counter<MethodBase>>();
  9. private readonly object _lock = new object();
  10. public void Increment(IInvocationInfo context)
  11. {
  12. var instance = context.Target;
  13. var targetMethod = context.TargetMethod;
  14. lock (_lock)
  15. {
  16. if (!_counts.ContainsKey(instance))
  17. _counts[instance] = new Counter<MethodBase>();
  18. _counts[instance].Increment();
  19. }
  20. }
  21. public void Decrement(IInvocationInfo context)
  22. {
  23. var instance = context.Target;
  24. var targetMethod = context.TargetMethod;
  25. if (!_counts.ContainsKey(instance))
  26. return;
  27. lock (_lock)
  28. {
  29. var counter = _counts[instance];
  30. counter.Decrement();
  31. // Remove the counter once it hits zero
  32. var modifiedCount = counter.GetCount();
  33. if (modifiedCount <= 0)
  34. _counts.Remove(instance);
  35. }
  36. }
  37. public int GetPendingCalls(IInvocationInfo context)
  38. {
  39. var result = 0;
  40. var instance = context.Target;
  41. var targetMethod = context.TargetMethod;
  42. if (!_counts.ContainsKey(instance))
  43. return 0;
  44. lock (_lock)
  45. {
  46. result = _counts[instance].GetCount();
  47. }
  48. return result;
  49. }
  50. }
  51. }