atiyar
atiyar

Reputation: 8338

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?

Upvotes: 0

Views: 659

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500495

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?

Upvotes: 3

Related Questions