Thanks for the info.
The scenario I'm working in is that of a graphics engine, where closely
managing resources is very important. There are times when a resource,
such as a texture, may not be needed for several seconds. But I don't
necessarily want the GC to swoop in and dispose it, as it may be needed
soon afterward and need to be reloaded.
So my thinking was that I'd have one reference to a texture or mesh or
something in a resourcemanager, and all other objects obtain references
to the resource from that resourcemanager. Each resource would have a
user defined time associated with it, say 30 seconds (which is an
eternity in graphics programming). Any time the reference count dropped
to one, the timer would start counting down. When the timer hits zero,
the resource manager removes its reference to the resource, which allows
the GC to swoop in and dispose of it.
The elegence of that solution would have been that other objects using
references to the resource wouldn't have needed to inform the manager
when they weren't using it any more.
I suppose I'll just have to go with an uglier solution where objects
have to inform the resourcemanager when they're obtaining or removing a
reference. The downside of course would be, that if the user forgets to
tell the manager when a reference has been removed, the resource will
never get disposed.
I suppose it's not so bad, it's just like pairing "new" and "delete []"
in c/c++.
Christoph Nahr <ch************@kynosarges.de> wrote in
news:q9********************************@4ax.com:
On Sun, 11 Dec 2005 09:25:17 GMT, Jason Bell <ce******@shaw.ca> wrote:
How can I find out how many references to an instance exist at any
given time?
You can't. The CLR memory manager doesn't work like that. Reference
counting leaves you open to cyclic references that cause memory leaks.
Instead, every garbage collection starts afresh and determines all
objects that are currently reachable by your program. I don't think
the actual number of references is ever counted.
I want to make it so that when the number of references is one, a
countdown starts (that one reference being the one held by the
resource manager). This way I can ensure that objects are only
deleted if they haven't been used in an amount of time defined by the
user.
Hmm... there's the System.WeakReference class which allows you to
track the garbage collection status of an object. You can't prevent
GC in this way, though, so I guess it's not what you want.
You can call System.GC.KeepAlive to prevent garbage collection of an
object within the scope of a method, if that helps you.
Other than that, you have to track references and timestamps manually.
There's no way to determine the current number of references, other
than making a WeakReference and checking for !IsAlive, and in that
case the object has already been garbage-collected.
Why exactly are you planning to interfere with normal garbage
collection, anyway?