blob: 85f2b473d82758b8d5dbfe4ac60178ecf5cb3320 (
plain)
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
60
61
62
63
64
|
using System;
using System.Collections.Generic;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#endif
using Newtonsoft.Json.Serialization;
namespace Newtonsoft.Json.Utilities
{
internal class ThreadSafeStore<TKey, TValue>
{
private readonly object _lock = new object();
private Dictionary<TKey, TValue> _store;
private readonly Func<TKey, TValue> _creator;
public ThreadSafeStore(Func<TKey, TValue> creator)
{
if (creator == null)
throw new ArgumentNullException("creator");
_creator = creator;
}
public TValue Get(TKey key)
{
if (_store == null)
return AddValue(key);
TValue value;
if (!_store.TryGetValue(key, out value))
return AddValue(key);
return value;
}
private TValue AddValue(TKey key)
{
TValue value = _creator(key);
lock (_lock)
{
if (_store == null)
{
_store = new Dictionary<TKey, TValue>();
_store[key] = value;
}
else
{
// double check locking
TValue checkValue;
if (_store.TryGetValue(key, out checkValue))
return checkValue;
Dictionary<TKey, TValue> newStore = new Dictionary<TKey, TValue>(_store);
newStore[key] = value;
_store = newStore;
}
return value;
}
}
}
}
|