2

If i iterate over a list of Weakreferences, how can i be sure, the reference still exists, after proofing via _ref.IsAlive?

For example i have this piece of code, where scopeReferences is a of Weakreferences:

foreach (var _ref in scopeReferences)
{
    if (_ref.IsAlive)
    {
        if (_ref.Target is ScriptScope)
        {
            // Is it alive any more?
            ((ScriptScope)_ref.Target).SetVariable(name, value);
        }
    }
}

Maybe some one knows the answer, i just don't want to create any problems due to the fact, i don't know what's going on in this part. Thank you all a lot!

BendEg
  • 20,098
  • 17
  • 57
  • 131
  • 1
    `IsAlive` is only usable for one thing and that is detecting that it is no longer alive. You have race conditions as you have already gathered for the other way around. – Lasse V. Karlsen Dec 22 '15 at 16:21

1 Answers1

6

You could copy it to a variable, after which you either have it or you don't, and you can safely test it:

foreach (var _ref in scopeReferences)
{
    ScriptScope tmp = _ref.Target as ScriptScope;
    if (tmp != null)
    {
        tmp.SetVariable(name, value);
    }
}
adv12
  • 8,443
  • 2
  • 24
  • 48