-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCachedCollection.cs
More file actions
46 lines (37 loc) · 1.08 KB
/
Copy pathCachedCollection.cs
File metadata and controls
46 lines (37 loc) · 1.08 KB
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
using System;
using System.Collections.Generic;
namespace DataKit.Modelling
{
public class CachedCollection<TKey, TValue>
{
private readonly object _syncronized = new object();
private readonly Dictionary<TKey, TValue> _cacheStore = new Dictionary<TKey, TValue>();
public bool TryGetValue(TKey key, out TValue value)
=> _cacheStore.TryGetValue(key, out value);
public TValue CreateIfNeeded(TKey key, Func<TValue> factory)
{
lock (_syncronized)
{
if (TryGetValue(key, out var value))
return value;
value = factory();
_cacheStore.Add(key, value);
return value;
}
}
}
public class CachedCollection<TKey, TFactoryArg, TValue> : CachedCollection<TKey, TValue>
{
private readonly Func<TFactoryArg, TValue> _factory;
public CachedCollection(Func<TFactoryArg, TValue> factory)
{
_factory = factory;
}
public TValue GetOrCreate(TKey key, TFactoryArg factoryArg)
{
if (TryGetValue(key, out var value))
return value;
return CreateIfNeeded(key, () => _factory(factoryArg));
}
}
}