-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathCacheEngineAsync.cs
70 lines (64 loc) · 2.53 KB
/
CacheEngineAsync.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
68
69
70
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Polly.Caching
{
internal static partial class CacheEngine
{
internal static async Task<TResult> ImplementationAsync<TResult>(
IAsyncCacheProvider<TResult> cacheProvider,
ITtlStrategy<TResult> ttlStrategy,
Func<Context, string> cacheKeyStrategy,
Func<Context, CancellationToken, Task<TResult>> action,
Context context,
CancellationToken cancellationToken,
bool continueOnCapturedContext,
Action<Context, string> onCacheGet,
Action<Context, string> onCacheMiss,
Action<Context, string> onCachePut,
Action<Context, string, Exception> onCacheGetError,
Action<Context, string, Exception> onCachePutError)
{
cancellationToken.ThrowIfCancellationRequested();
string cacheKey = cacheKeyStrategy(context);
if (cacheKey == null)
{
return await action(context, cancellationToken).ConfigureAwait(continueOnCapturedContext);
}
TResult valueFromCache;
try
{
valueFromCache = await cacheProvider.GetAsync(cacheKey, cancellationToken, continueOnCapturedContext).ConfigureAwait(continueOnCapturedContext);
}
catch (Exception ex)
{
valueFromCache = default(TResult);
onCacheGetError(context, cacheKey, ex);
}
if (valueFromCache != null && !valueFromCache.Equals(default(TResult)))
{
onCacheGet(context, cacheKey);
return valueFromCache;
}
else
{
onCacheMiss(context, cacheKey);
}
TResult result = await action(context, cancellationToken).ConfigureAwait(continueOnCapturedContext);
Ttl ttl = ttlStrategy.GetTtl(context, result);
if (ttl.Timespan > TimeSpan.Zero && result != null && !result.Equals(default(TResult)))
{
try
{
await cacheProvider.PutAsync(cacheKey, result, ttl, cancellationToken, continueOnCapturedContext).ConfigureAwait(continueOnCapturedContext);
onCachePut(context, cacheKey);
}
catch (Exception ex)
{
onCachePutError(context, cacheKey, ex);
}
}
return result;
}
}
}