-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCacheable.cs
More file actions
57 lines (50 loc) · 1.39 KB
/
Copy pathCacheable.cs
File metadata and controls
57 lines (50 loc) · 1.39 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
47
48
49
50
51
52
53
54
55
56
57
using System;
namespace ScrobbleMapper
{
/// <summary>
/// Kinda like a LazyInit, but with writing capability
/// </summary>
class Cacheable<T>
{
bool stale = true;
T cache;
readonly Func<T> refresher;
readonly Action<T> updater;
/// <param name="refresher">A function that refreshes the field from the data storage</param>
/// <param name="updater">A function that writes new local data to the data storage</param>
public Cacheable(Func<T> refresher, Action<T> updater)
{
this.refresher = refresher;
this.updater = updater;
}
/// <summary>
/// Marks this instance as out-of-sync with the data storage
/// </summary>
public void Invalidate()
{
stale = true;
}
public T Value
{
get
{
if (stale)
{
cache = refresher();
stale = false;
}
return cache;
}
set
{
updater(value);
cache = value;
stale = false;
}
}
public static implicit operator T(Cacheable<T> cached)
{
return cached.Value;
}
}
}