alastairtree / LazyCache

An easy to use thread safe in-memory caching service with a simple developer friendly API for c#
https://nuget.org/packages/LazyCache
MIT License
1.72k stars 159 forks source link

How Do I Clear, Expire, or Refresh a Cached Item On an Event? #144

Closed PostAlmostAnything closed 3 years ago

PostAlmostAnything commented 3 years ago

I have a feature on an old ASP.Net WebForms site for users to post comments. I am implementing LazyCache and want to serve comments from the cache, but this creates a bad user experience if they post a comment because the list of comments does not include their latest comment right away.

How do I clear the cache for comments whenever a new comment is posted? I tried disposing of the provider but that results in a runtime error saying that a disposed object cannot be accessed.

I would like to refresh the comments cache ideally by adding some code to the comment inserted event that removed the cache based on the cache key of the comments.

alastairtree commented 3 years ago

In your use case you could cache the comments with a key based on the id of the page on which the comments appear, such as comments-page-01. When a new comment is added to that page then you should just remove that key from the cache:

//Add the comment to page PageId

// Get the cache (better to use dependency injection)
IAppCache cache = new CachingService();

// Remove the pages comments from the cache
cache.Remove($"comments-page-{PageId}");

More info in the docs

alastairtree commented 3 years ago

Closing as inactive,