Jump to content
  • Advertisement
Sign in to follow this  
Holy Fuzz

[.net] WeakReferences keeping objects alive?

This topic is 4881 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hey all, here's an interesting problem: I'm writing a game in C#, and I realized that I was having a .Net-style memory leak because whenever I start a new game (without exitting the app) my memory usage increases by a few megs. So obviously I'm still referencing somthing from the precious game that shouldn't be referenced anymore. So I pulled out the CLR Profiler from Microsoft, started the app, started a new game, and then restarted that game, at which point I did a heap dump so that I could look at my heap. If you don't know how the CLR Profiler works, doing a heap dump gives you a nice graph where you can see what objects reference other objects. To my surprise, the CLR root was directly referencing a number of my objects from the previous game, which kept everything from it alive. None of these objects SHOULD be referenced by the CLR root, so I did a little more investigating, and quickly realized that ALL of these objects are referenced by WeakReferences at some point in time. And if I change my code so that one of those objects is NOT referenced by a WeakReference, then it magically disappears from the list of objects that the CLR root references. So now I'm stumped. Any ideas? Thanks. - Fuzz

Share this post


Link to post
Share on other sites
Advertisement
Weakreferences are kept in a special collection (cache). These only get destroyed when the object the weakreference is referencing is removed from memory. Read this.

Cheers

Share this post


Link to post
Share on other sites
Yeah, I know how weak references work. It turns out that wasn't the problem - the CLR profiler was showing all my weak-referenced objects as being kept alive by the CLR root, when they were in fact being kept alive by other means.

Thanks anyway.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!