简体   繁体   中英

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?

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM