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

Dispose entry when evicted #89

Closed Refresh06 closed 4 years ago

Refresh06 commented 5 years ago

Rather surprised to see that disposable objects are not disposed after eviction, which in my mind would seem natural. Any reason this has not been implemented?

I know I can use an eviction callback to perform the disposal, it just seems a pretty basic requirement,

Magnus12 commented 4 years ago

What if you have an eviction callback that needs to perform some action on the objects. Than you wouldn't want them to be disposed.

Refresh06 commented 4 years ago

You would just do what you need to do in the dispose method. In the rare case that you need to perform some special action on cache eviction only, you could easily wrap the object in an IDisposable that performed the needed action and might not even dispose the inner object if that is what you need for some weird situation that I can't really imagine. Actually i think making the cache dispose disposables would make eviction callbacks redundant.

alastairtree commented 4 years ago

What are you caching that needs disposing? If you are holding onto resources that maintain connections or external resources using LazyCache then you probably should not be caching those - you should manage those lifetimes manually as they are expensive. Cached items do not have deterministic lifetimes - they could be evicted early because of memory pressure, or late becasue nothing has called the cache and triggered an cache eveiction clean up - neither of which is good for expensive IDisposable resources like database connections.

For example I would advise you not to cache something that holds a connection to a database. Instead cache the query result and reuse the result, and close/clean up the database connection or return it to the conection pool imediately after the query result is fetched.

Also LazyCache cannot know he lifetime setup for your objects - you might be using dependency injection to manage disposables lifetimes and cleanup logic or you might be disposing manually due to some user behaviour - we cannot know. So if you need explicit disposal you need to code that yourself using eveiction callbacks.

In general items eveicted from the cache will get picked up by the garbage collector after some time. if you have to dipose them, you need to code that.

Hope that helps explain why currently we do not do the disposal automatically on IDisposables.