views:

21

answers:

1

I'm creating a simple messaging system for a windows phone silverlight app.

The idea is various xaml pages & other objects will subscribe to a messaging object, passing in the type of message they want to recieve/handle and an Action<> Delegate as the handler.

When an action happens a message (with payload) will be sent to the correct subscribers.

Here's a quick draft of what I want as the message class.

public class MessageBus
{
    private List<Subscriber> subscribers;

    public MessageBus()
    {
        subscribers = new List<Subscriber>();
    }

    public void Subscribe(string messageType, Action<object>subscriber){
        subscribers.Add(new Subscriber(messageType, subscriber));
    }

    public void SendMessage(object message, string messageType)
    {
        foreach (Subscriber subscriber in subscribers)
        {
            if (subscriber.MessageType == messageType && subscriber.Reciever  != null)
            {
                subscriber.Reciever(message);
            }
        }
    }

}

public class Subscriber
{
    public string MessageType { get; set; }
    public Action<object> Reciever { get; set; }

    public Subscriber(string messageType, Action<Object> reciever)
    {
        MessageType = messageType;
        Reciever = reciever;
    }

}

So varius subscribers will add themselves with a type, Action. As I understand this will stop the original pages/objects from being garbage collected (I assume it would be otherwise?) because a reference to it will always exist.

I can't really unsubscribe, or not always anyway and the messaging queue will stay around for the lifetime of the application.

Should I implement WeakReferences and if so how?

Would WeakReferences add more overhead?

Am I crazy to even consider this because the memory in use will be tiny?

A: 

The MVVM Light toolkit has a fantastic loosely coupled messaging bus and it's available for WP7 http://www.galasoft.ch/mvvm/getstarted/

You may need this: http://blog.galasoft.ch/archive/2010/07/22/mvvm-light-hotfix-for-windows-phone-7-developer-tools-beta.aspx

Doobi