forked from sarbian/ModuleManager
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKeyValueCache.cs
More file actions
29 lines (27 loc) · 850 Bytes
/
Copy pathKeyValueCache.cs
File metadata and controls
29 lines (27 loc) · 850 Bytes
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
using System;
using System.Collections.Generic;
namespace ModuleManager.Collections
{
public class KeyValueCache<TKey, TValue>
{
private readonly Dictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>();
private readonly object lockObject = new object();
public TValue Fetch(TKey key, Func<TValue> createValue)
{
if (createValue == null) throw new ArgumentNullException(nameof(createValue));
lock(lockObject)
{
if (dict.TryGetValue(key, out TValue value))
{
return value;
}
else
{
TValue newValue = createValue();
dict.Add(key, newValue);
return newValue;
}
}
}
}
}