Quantcast
Channel: Recent Threads — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 204402

Difference between using MessagingCenter and event handlers

$
0
0

I can't seem to find this answer anywhere, so I thought I'd ask here -- 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?


Viewing all articles
Browse latest Browse all 204402

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>