-
Notifications
You must be signed in to change notification settings - Fork 0
/
WebCacheRepository.cs
67 lines (56 loc) · 2.03 KB
/
WebCacheRepository.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
58
59
60
61
62
63
64
65
66
67
using System;
using System.Collections;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;
using CacheRepository.Configuration;
using CacheRepository.Implementation.Base;
namespace DataCachingApp
{
public class WebCacheRepository : AsyncCacheRepositoryBase
{
private readonly Cache _cache;
public WebCacheRepository(ICacheSettings cacheSettings)
: base(cacheSettings)
{
_cache = HttpContext.Current == null
? HttpRuntime.Cache
: HttpContext.Current.Cache;
}
public override Task RemoveAsync(string key, CancellationToken cancelToken)
{
_cache.Remove(key);
return Task.FromResult(true);
}
public override Task ClearAllAsync(CancellationToken cancelToken)
{
var keys = _cache
.Cast<DictionaryEntry>()
.Select(entry => entry.Key.ToString())
.ToArray();
foreach (var key in keys)
_cache.Remove(key);
return Task.FromResult(true);
}
protected override Task<Tuple<bool, T>> TryGetAsync<T>(string key, CancellationToken cancelToken)
{
var getValue = _cache.Get(key);
var notNull = getValue != null;
var value = notNull ? (T) getValue : default(T);
var result = Tuple.Create(notNull, value);
return Task.FromResult(result);
}
protected override Task SetAsync<T>(string key, T value, DateTime? expiration, TimeSpan? sliding, CancellationToken cancelToken)
{
if (sliding.HasValue)
_cache.Insert(key, value, null, Cache.NoAbsoluteExpiration, sliding.Value);
else if (expiration.HasValue)
_cache.Insert(key, value, null, expiration.Value, Cache.NoSlidingExpiration);
else
_cache.Insert(key, value);
return Task.FromResult(true);
}
}
}