Question about WeakReferences

Posted by Impz0r on Stack Overflow See other posts from Stack Overflow or by Impz0r
Published on 2010-05-15T15:49:42Z Indexed on 2010/05/15 15:54 UTC
Read the original article Hit count: 366

Filed under:

Hey there,

I've got a question regarding WeakReferences.

I'm right now in the process of writing a "Resource Manager" who hast to keep references to created texture objects. I have a Dictionary like:

Dictionary<uint, WeakReference>

Where the first is, as you allready may guessed, the Resource Id and the second param is a WeakReference to the Resource itself.

Right now my Resources do have a method to free themselfes from their Owner (i.e. Resource Manager). They do so in calling a method at the Resource Manger while passing a this reference to it. The ResMgr does lookup if it is a resource he keeps bookmark of and if so, does something like this:

WeakReference result;
if (m_Resources.TryGetValue(ResourceId, out result))
{
  if (result.IsAlive)
   return;

  (result.Target as Resource).free(); // free for good

  m_Resources.Remove(ResourceId);
}

The Problem I'm having is that the part after:

if (result.IsAlive)

is never reached because there are still leftover references to the Resource.

The thing is, I do only have one Reference of the Resource in question and it releases itself like:

resource.free(); // calls internally its owner (i.e. ResMgr)
resource = null;

I guess the left over reference would be the "resource" variable, but I cannot set it to null, because I do have to call free first. Quite a dilema...

Well what I wanted to achive with this is a Resource Manager who keeps references to its owning Resources and release them ONLY if there is no reference left to not screw up something.

Any idea how I may solve this in a clean fashion?

Thanks in advance!

Mfg Imp

© Stack Overflow or respective owner

Related posts about c#