Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ private sealed class CacheEntryTokens
internal List<IChangeToken> ExpirationTokens => _expirationTokens ??= new List<IChangeToken>();
internal List<PostEvictionCallbackRegistration> PostEvictionCallbacks => _postEvictionCallbacks ??= new List<PostEvictionCallbackRegistration>();

internal void AttachTokens()
internal void AttachTokens(CacheEntry cacheEntry)
{
if (_expirationTokens != null)
{
Expand All @@ -35,7 +35,7 @@ internal void AttachTokens()
if (expirationToken.ActiveChangeCallbacks)
{
_expirationTokenRegistrations ??= new List<IDisposable>(1);
IDisposable registration = expirationToken.RegisterChangeCallback(ExpirationCallback, this);
IDisposable registration = expirationToken.RegisterChangeCallback(ExpirationCallback, cacheEntry);
_expirationTokenRegistrations.Add(registration);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ bool FullCheck(in DateTimeOffset offset)
}
}

internal void AttachTokens() => _tokens?.AttachTokens();
internal void AttachTokens() => _tokens?.AttachTokens(this);

private static void ExpirationTokensExpired(object obj)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,35 @@ public void TokenExpiresOnRegister()
Assert.Null(result);
}

[Fact]
public void PostEvictionCallbacksGetInvokedWhenMemoryCacheEntriesExpireWithAnActiveChangeToken()
{
using var cache = new MemoryCache(new MemoryCacheOptions());
var key = new object();

var cts = new CancellationTokenSource();
var callbackInvoked = new ManualResetEvent(false);

cache.Set(key, new object(), new MemoryCacheEntryOptions
{
ExpirationTokens = { new CancellationChangeToken(cts.Token) },
PostEvictionCallbacks =
{
new PostEvictionCallbackRegistration()
{
EvictionCallback = (key, value, reason, state) => ((ManualResetEvent)state).Set(),
State = callbackInvoked
}
}
});

Assert.True(cache.TryGetValue(key, out _));

cts.Cancel();
Assert.True(callbackInvoked.WaitOne(TimeSpan.FromSeconds(10)));
Assert.False(cache.TryGetValue(key, out _));
}

internal class TestToken : IChangeToken
{
private bool _hasChanged;
Expand Down