Problem?

Jul 4, 2011 at 5:54 AM

 private void Prune()
        {
            var commands = _map.Keys.ToList();
            for (var commandIndex = commands.Count - 1; commandIndex > -1; --commandIndex)
            {
                var commandRef = commands[commandIndex];
                if (!commandRef.IsAlive)
                {
                    _map.Remove(commandRef);
                }
                else
                {
                    var buttons = _map[commandRef];
                    for (var buttonIndex = buttons.Count - 1; buttonIndex > -1; --buttonIndex)
                    {
                        var buttonRef = buttons[buttonIndex];
                        if (!buttonRef.IsAlive)
                        {
                            buttons.RemoveAt(buttonIndex);
                        }
                    }
                }
            }
   I think this code will be overflow range?

Jul 4, 2011 at 6:01 AM

I solve such szenarios by getting a copy of the first collection and then remove alle elements in the copied colleciton from the first.

 

btw when using weakrefs (I assume you are doing in this sample) . It's important to not rely on the IsAlive Property.

Because it can change right between the check and the next lien of code.

 

It's  a much better pattern to obtain a reference to a local variable and then  check if it is null .

As long as the local variable exists the object behind the won't get lost

Like this:

 

var myRef = buttons[buttonIndex];

if(myRef != null)
{

}
Jul 4, 2011 at 7:40 AM

:)