Skip to content

Are CancellationTokenSources triggered when invalidated from cache? Hope so! #12828

@johnnyreilly

Description

@johnnyreilly

Consider the following:

_cache.Get<CancellationTokenSource>(CacheKeys.DependentCTS).Cancel();

Here, we're manually acquiring a cached CancellationTokenSource and calling Cancel. This will invalidate the cache for anyone using that token, eg people who have done this:

    var cts = new CancellationTokenSource();
    _cache.Set(CacheKeys.DependentCTS, cts);

    using (var entry = _cache.CreateEntry(CacheKeys.Parent))
    {
        // expire this entry if the dependant entry expires.
        entry.Value = DateTime.Now;
        entry.RegisterPostEvictionCallback(DependentEvictionCallback, this);

        _cache.Set(CacheKeys.Child,
            DateTime.Now,
            new CancellationChangeToken(cts.Token));
    }

It's not clear from the docs whether, when the cached CancellationTokenSource is expired from the cache, whether that has the effect of triggering all the dependant cached entries to be invalidated too. For instance, if I'm only caching my CancellationTokenSource for 5 minutes, I'd love when it's being evacuated from the cache for all the dependents to go with it. But I don't know whether cache evacuation will trigger the .Cancel() on the token. It's certainly my hope that is the behaviour but I'd love the docs to be clear on that.

I suspect that isn't what happens as it's a bit "magical"

At the moment, the way I read it, it suggests that only calling _cache.Get<CancellationTokenSource>(CacheKeys.DependentCTS).Cancel(); will trigger the invalidation; ie it has to be explicitly triggered. If that is the case, then guidance on how to do that would improve these docs I think. My guess would be that this would be this would be done using RegisterPostEvictionCallback if that's the case?

PS great work on the docs generally - they're really good!

https://docs.microsoft.com/en-us/aspnet/core/performance/caching/memory?view=aspnetcore-2.2#cache-dependencies


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Source - Docs.msDocs Customer feedback via GitHub Issuearea-runtime-extensionsIssues related to Microsoft.Extensions libraries that reside in dotnet/runtimeproduct-questionre-Aditya@adityamandaleeka must review

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions