-
Notifications
You must be signed in to change notification settings - Fork 331
/
Copy pathRefCounter.cs
59 lines (44 loc) · 1.64 KB
/
RefCounter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
namespace EasyCaching.Core.DistributedLock
{
internal class RefCounter<T>
{
private int _refCount = 1;
public RefCounter(T value) => Value = value;
public T Value { get; }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int Increment() => Interlocked.Increment(ref _refCount);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int Decrement() => Interlocked.Decrement(ref _refCount);
}
internal class RefCounterPool<TKey, TValue> where TValue : class
{
private readonly IDictionary<TKey, RefCounter<TValue>> _dictionary;
public RefCounterPool() => _dictionary = new Dictionary<TKey, RefCounter<TValue>>();
public TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory)
{
if (valueFactory == null) throw new ArgumentNullException(nameof(valueFactory));
RefCounter<TValue> item;
lock (_dictionary)
{
if (!_dictionary.TryGetValue(key, out item))
return (_dictionary[key] = new RefCounter<TValue>(valueFactory(key))).Value;
}
item.Increment();
return item.Value;
}
public TValue TryRemove(TKey key)
{
RefCounter<TValue> item;
lock (_dictionary)
{
if (!_dictionary.TryGetValue(key, out item) || item.Decrement() > 0) return null;
_dictionary.Remove(key);
}
return item.Value;
}
}
}