0

Given that there is a dictionary where a sequence of instances are maintained. Although such instances may remain unused for a considerably long time, since they are referred to by the dictionary (or any other collection type) and due to the fact that a reference to that dictionary is kept alive by its parent, the GC does not attempt to automatically collect such items inside of the collection.

The problem is that, since such instances keep accumulating inside of the collection and remain untouched by the GC, a system may run short in memory after a period of time.

Is there a standard pattern to automatically identify these sorts of unused objects inside of a collection and report them to the garbage collector? (Please note that a GC.Collect() will is totally useless in this case, alongside with being poisonous for the rest of the code)

Arnold Zahrneinder
  • 4,788
  • 10
  • 40
  • 76
  • 4
    The object *isn't* unused. As you say, there's a reference to it in the collection. – Jon Skeet Apr 19 '21 at 11:10
  • @JonSkeet: That is correct, what I meant is literally unused. – Arnold Zahrneinder Apr 19 '21 at 11:11
  • 3
    What would you expect to happen if you then *did* try to use the dictionary entry? If you don't need it any more, remove it from the dictionary. You *may* find that `WeakReference` is what you want (keep weak references in your dictionary entries instead of strong references) but there isn't enough information in the question in terms of what you want to happen, for us to say that. – Jon Skeet Apr 19 '21 at 11:14
  • 2
    The standard pattern is to remove the objects from the dictionary when you don’t need them anymore. – Holger Apr 19 '21 at 11:14
  • It sounds like you're trying to implement a cache. How about this? https://learn.microsoft.com/en-us/aspnet/core/performance/caching/memory?view=aspnetcore-5.0 – DavidG Apr 19 '21 at 11:15
  • @JonSkeet: Thank you sir! `WeakReference` is what I was looking for! – Arnold Zahrneinder Apr 19 '21 at 11:17
  • What is the actual goal you are trying to achieve? [`weakreference` is not a great idea for caching](https://stackoverflow.com/questions/930198/does-weakreference-make-a-good-cache) since you will have no control over the lifetime of the objects. – JonasH Apr 19 '21 at 12:48
  • @JonasH: The goal is not caching, I needed to create a customized scope management system. – Arnold Zahrneinder Apr 19 '21 at 13:26

0 Answers0