Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

reflection - C# - Get number of references to object

I'm trying to write a simple Resource Manager for the little hobby game I'm writing. One of the tasks that this resource manager needs to do is unloading unused resources. I can think of doing this in two ways:

  • When an object no longer requires a reference to the resource, it must call a method of the Resource Manager to signify it is no longer using it; or

  • When an object no longer requires a reference to the resource, it simply sets it to null. Then when the Resource Manager is asked to unload unused resources, it gets the reference count (via reflection?) of each resource. If the reference count is one (the Resource Manager will have a reference to the resource), unload the resource.

Is there any way to acheive the second solution in C#? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Couple things. First off, objects are not reference counted; reference counting schemes have the circular reference problem, whereby two objects refer to each other but are otherwise inaccessible, and thereby leak. .NET uses a mark-and-sweep approach which does not use ref counts.

Second, though the suggestion to use a weak reference is not terrible, it's also not a slam dunk. You are building a cache for performance reasons. (I assume that your careful, empirical, realistic research into the performance characteristics of your application has convincingly demonstrated that a caching strategy is necessary in order to achieve acceptable performance; if that's not the case, then you are making these decisions prematurely.) Every cache has to have a POLICY about when it releases its resources, otherwise it's a memory leak.

How do you know that the GC policy and your policy are equivalent policies? The GC was not designed with your specific performance needs in mind. That is, it was designed to release resources that really are garbage, not to achieve any particular performance goal you've got in mind. By delegating the decision to the GC, you give up your ability to tune your cache policy to your performance needs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...