Search code examples
c#.netgarbage-collectionweak-references

How to get the target of a weak reference in a safe way


Consider this code:

var weakRef = new WeakReference(new StringBuilder("Mehran"));
if (weakRef.IsAlive)
{
    // Garbage Collection might happen.
    Console.WriteLine((weakRef.Target as StringBuilder).ToString());
}

It's possible for GC.Collect to run after checking weakRef.IsAlive and before using the weakRef.Target.

Am I wrong with this? If it's possible, ss there a safe way to do that?

For example an API like weakRef.GetTargetIfIsAlive() would be appropriate.


Solution

  • That API already exists; weakRef.Target returns null if the object has already been garbage collected.

    StringBuilder sb = weakRef.Target as StringBuilder;
    if (sb != null)
    {
        Console.WriteLine(sb.ToString());
    }