Search code examples
c#garbage-collectiondisposeobject-reference

How to check at runtime if an object is currently being used by the application, or has been garbage-collected?


The question pretty much says it all. Somewhere in my code i instantiated an object ObjectX with the new keyword. Now ObjectX is an expensive one in terms of memory and other resources. I need a means to check at runtime whether ObjectX is currently alive and being used by the application, or has been garbage-collected.
Any attempt to use a reference to the object is gonna make the object being used. So how can do i that?


Solution

  • Well, you could keep a WeakReference to it. That won't stop it from being garbage collected, and you can check its "liveness" with IsAlive.

    It's generally a bit of a design smell if you need this sort of thing though. Why do you need to perform this check?