WeakAction class not creating weak reference with target in Silverlight

Feb 23, 2015 at 4:09 AM
Hi,
I am using Assembly GalaSoft.MvvmLight.dll, Version v5.0.2.32242
Created a demo application for Mediator pattern, but WeakAction class using strong reference instead of weak reference, Which leads to memory leak.
In Silverlight I am using following class to hold the Action
public class ActionHolder
{
    public WeakAction<Object> Callback { get; private set; }
    public ActionHolder(WeakAction<Object> callback, string filter)
    {
        this.Callback = callback;
    }
}
and using other class to Register and Notify actions
     public sealed class Mediator
    {
        private static readonly Mediator _instance = new Mediator();
        private Dictionary<object, ActionHolder> _actions = new Dictionary<object, ActionHolder>();

        public void Register(object message, WeakAction<Object> callback)
        {
            _actions.AddValue(message, new ActionHolder(callback, null));
        }

        private void Notify(object message, object args, string filter)
        {
            if (_actions.ContainsKey(message))
            {
                List<ActionHolder> actionHolders = _actions[message].ToList();
                foreach (ActionHolder actionHolder in actionHolders)
                {
                    bool notifyAll = filter == null;

                    if (notifyAll || !string.IsNullOrEmpty(actionHolder.Filter) && actionHolder.Filter.Equals(filter))
                    {
                        actionHolder.Callback.Execute(args);
                    }
                }
            }
        }

    }
WeakAction class is creating strong reference, is WeakAction class is working in silverlight or designed only for WPF ?

Thanks,
Gurpreet
Coordinator
Feb 23, 2015 at 9:28 AM
Edited Feb 23, 2015 at 9:29 AM
Hi,

Silverlight's security model is more restrictive, so in Silverlight, if your method is private or internal, the WeakAction has to fall back to a strong reference instead of a weak one. It is annoying but there is not much we can do there. You can declare your method as a public and this should solve the issue. Note that the problem is only in Silverlight. All other frameworks support private methods in weak action.

Also, anonymous lambdas are private, so in Silverlight you can also not use an anonymous lambda.

Cheers Laurent
Feb 23, 2015 at 11:29 AM
Hi Laurent,

Thanks for the quick reply. It solved my problem.

Cheers,
Gurpreet