In this case, your cache should not cache the actual object, but rather a wrapper around the cached object, which also contains information about the state of the object in the cache.
For example, you might have a simple class that represents elements in the cache:
public class CacheItem<T> {
The idea here is simple:
When your cache is about to introduce a new instance of an element into the cache, it calls the constructor (the constructor should be accessible only to the cache, if necessary, you can make CacheItem nested class with a private constructor instead of the internal one), which sets the value of the IsCached property to true. Then the item is cached.
When an item expires from the cache, the cache sets the IsCached property to false (again, this property should be available only to the cache).
Responsibility is transferred to the client to check the CacheItem<T> to make sure it is out of date.
Please note that this is a pull operation. If you want, you can add support for push operations by adding an event to the CacheItem<T> like this:
public class CacheItem<T> {
Now you can subscribe to Expired subscribers who tell clients when the cache entry is invalid. This is triggered by the cache, triggering an internal Expire event on the element when it is removed from the cache (and it also sets the IsCached property).
source share