-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
ObjectCacheExtensions.cs
57 lines (52 loc) · 1.75 KB
/
ObjectCacheExtensions.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
using System;
using System.Runtime.Caching;
namespace System.Runtime.Caching
{
public static class ObjectCacheExtensions
{
public static T Get<T>(ObjectCache cache, string key, T @default = default(T))
{
object cachedItem = cache.Get(key);
if (cachedItem is T t)
return t;
return @default;
}
public static bool TryGetValue<T>(ObjectCache cache, string key, out T value)
{
object cachedItem = cache.Get(key);
if (cachedItem is T t)
{
value=t;
return true;
}
value = default(T);
return false;
}
public static T AddOrGetExisting<T>(ObjectCache cache, string key, T item, CacheItemPolicy policy)
{
object cachedItem = cache.Get(key);
if (cachedItem is T t)
return t;
cache.Add(key, item, policy);
return item;
}
public static T AddOrGetExisting<T>(ObjectCache cache, string key, Func<(T item, CacheItemPolicy policy)> addFunc)
{
object cachedItem = cache.Get(key);
if (cachedItem is T t)
return t;
(T item, CacheItemPolicy policy) = addFunc();
cache.Add(key, item, policy);
return item;
}
public static T AddOrGetExisting<T>(ObjectCache cache, string key, Func<string, (T item, CacheItemPolicy policy)> addFunc)
{
object cachedItem = cache.Get(key);
if (cachedItem is T t)
return t;
(T item, CacheItemPolicy policy) = addFunc(key);
cache.Add(key, item, policy);
return item;
}
}
}