MVVM Light and PRISM offer messenger to implement event system.
the approximate interface looks like the following one:
interface Messanger
{
void Subscribe<TMessageParam>(Action<TMessageParam> action);
void Unsubscribe<TMessageParam>(Action<TMessageParam> action);
void Unsubscribe<TMessageParam>(objec actionOwner);
void Notify<TMessageParam>(TMessageParam param);
}
Now this model seems beneficial comparing to classic .net events. It works well with Dependency Injection. Actions are stored as weak references so memory leaks are avioded and unsubscribe is not a must.
The only annoyance is the need to declare new TMessageParam for each specific message.
But everything comes at a cost. And what I’m really worried about is that I see no shortcomings of this approach.
Has anoyne the experience of some troubles with this design pattern?
Update
We tried it and the most unpleasant thing with messages is their implicitness from the point of view of interface. Messages contrary to Events are not exposed explicitly in the interface so additional documentation must be provided.
As Laurent said below very loose coupling comes at a cost of vagueness.
One of the native .NET event’s attributes is that it’s immutable, which makes their access locklessly thread-safe. I’m guessing the same can’t be said of this implementation you’re referring to, though it may handle the locks under the covers for you so at least you don’t have to. Alternatively it may have it’s own form of immutable access (is the interface implemented on a value type?) but doing something of that nature is quite tricky in C# which is why events have always had language level support.
Other than that, there may be performance differences between the two but I can’t say for certain one way or the other, and further there is the fact of the syntax which is not available in your mentioned approach.
3
The major disadvantage of messaging-based systems is that it is less easy to understand what’s going on. It can be tougher to debug what’s happening than in an event based system, exactly because the messaging system is more loosely coupled. It’s the same type of issue that comes with advanced systems like Rx (Reactive extensions).
1