Skip to content

Commit 4654645

Browse files
author
László Jakab
committed
Remove cancellation token from memory cache
1 parent e7ce050 commit 4654645

File tree

1 file changed

+3
-31
lines changed

1 file changed

+3
-31
lines changed

src/AutSoft.Core/Caching/MemoryCacheExtensions.cs

Lines changed: 3 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
using Microsoft.Extensions.Caching.Memory;
2-
using Microsoft.Extensions.Primitives;
32

43
namespace AutSoft.Common.Caching;
54

@@ -8,8 +7,6 @@ namespace AutSoft.Common.Caching;
87
/// </summary>
98
public static class MemoryCacheExtensions
109
{
11-
private const string Postfix = "CancellationTokenSource";
12-
1310
/// <summary>
1411
/// Get or create a cached element with error handling
1512
/// </summary>
@@ -30,7 +27,6 @@ public static async Task<TItem> GetOrCreateWithErrorHandlingAsync<TItem>(
3027
return await cache.GetOrCreateAsync(key, entry =>
3128
{
3229
entry.SetOptions(options);
33-
entry.AddExpirationToken(cache.CreateToken(key));
3430
return factory(entry);
3531
});
3632
}
@@ -60,9 +56,8 @@ public static void SetWithErrorHandling<TItem>(
6056
try
6157
{
6258
using var entry = cache.CreateEntry(key);
63-
entry.Size = size;
6459
entry.SetOptions(options);
65-
entry.AddExpirationToken(cache.CreateToken(key));
60+
entry.Size = size;
6661
entry.Value = value;
6762
}
6863
catch
@@ -88,34 +83,11 @@ private static void SetOptions(this ICacheEntry entry, MemoryCacheEntryOptions?
8883
}
8984
}
9085

91-
private static IChangeToken CreateToken(this IMemoryCache cache, string key)
92-
{
93-
var tokenSourceKey = key + Postfix;
94-
95-
var source = cache.Set(
96-
tokenSourceKey,
97-
new CancellationTokenSource(),
98-
new MemoryCacheEntryOptions { Size = 1 });
99-
100-
return new CancellationChangeToken(source.Token);
101-
}
102-
10386
/// <summary>
10487
/// Invalidate a cached element's value
10588
/// </summary>
10689
/// <param name="cache">An <see cref="IMemoryCache"/> object</param>
10790
/// <param name="key">The key of the cached element</param>
108-
/// <returns>The element invalidated successfully or not</returns>
109-
public static bool Invalidate(this IMemoryCache cache, string key)
110-
{
111-
var tokenSourceKey = key + Postfix;
112-
113-
if (!cache.TryGetValue(tokenSourceKey, out CancellationTokenSource source))
114-
return false;
115-
116-
source.Cancel();
117-
cache.Remove(tokenSourceKey);
118-
119-
return true;
120-
}
91+
public static void Invalidate(this IMemoryCache cache, string key)
92+
=> cache.Remove(key);
12193
}

0 commit comments

Comments
 (0)