PageRenderTime 82ms CodeModel.GetById 40ms app.highlight 4ms RepoModel.GetById 37ms app.codeStats 0ms

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