Search code examples
c#.neteventsxamarin.formsmessagingcenter

What is the difference between using MessagingCenter and standard .NET event handlers for informing interested parties of changes?


What is the difference between using MessagingCenter and standard .NET event handlers for informing interested parties of changes?

Two (untested) implementations of the same thing are below to demonstrate:

public class FooClass {
  public event EventHandler SomeEvent;

  public void DoSomeWork() {
     // ... stuff
    if(SomeEvent != null)
      SomeEvent(this, EventArgs.Empty);
  }
}

public class BarClass {
  FooClass _foo;

  public BarClass() {
    _foo = new FooClass();
    _foo.SomeEvent += delegate {
      // ... did something
   };
  }
}

Verses:

public class FooClass {
  public const string SomeEventName = "SomeEvent";
  public void DoSomeWork() {
    // ... stuff
    MessagingCenter.Send<FooClass>(this, SomeEventName);
  }
}

public class BarClass : IDisposable {
  public BarClass() {
    MessagingCenter.Subscribe<FooClass>(this, FooClass.SomeEventName, delegate {
      // .. did something
   });
  }

  public void Dispose() {
    MessagingCenter.Unsubscribe<FooClass>(this, FooClass.SomeEventName);
  }
}

From what I can tell there doesn't seem to be any difference, but if anyone can suggest any pros or cons for either, that'd help me understand. Currently, I've been using event handlers.

Is there any point in switching to using MessagingCenter? Or any new best practice?


Solution

    • MessagingCenter is basically used in the Model-View-ViewModel pattern.
    • It is a great way to communicate and pass data or notify about updates among ViewModels without knowing who sent it to whom via a simple Message Contract.
    • Ex. In one screen if you make any service call to fetch the new data and you want to notify other screens to update their UI via broadcasting message from your current screen, then MessagingCenter is the best approach.
    • It decouples them without making any dependency among ViewModels, while EventHandlers makes dependency and may prohibit something from being released. You explicitly have to decouple event handlers from the events to better release the resources.
    • MessagingCenter should be applied when the receiver doesn't care who sent the message and the sender doesn't care who will receive it. Events should be used when the receiver needs to know who sent the message, but the sender still doesn't care who handles it.
    • It is good to use MessagingCenter over Events but, if you make too much use of too many Messages using MessagingCenter, it would be hard to identify who sent it and when sent it, the relation between messages would be hard to guess, thus making it hard time while debugging the app.