user496949
user496949

Reputation: 86185

to pass data around using event handling

Anyone can detail the pros and cons to pass data from one class to another using event mechanism? When is the best time to use event to pass data?

Upvotes: 1

Views: 627

Answers (2)

Jón Trausti Arason
Jón Trausti Arason

Reputation: 4698

Let's take an example. You have a system where 20 people are subscribed to a weather station for changes in weather. Do you want the weather station to keep track of all the people and services that are subscribed?

In my opinion the weather station should not know anything about the people or services that are waiting for weather changes. The weather station should just dispatch an event, and whoever is listening to it will get notified :-)

So the point is, you use events to notify observers about an action or state change that occurred in the object. Observers can be difference type of objects since you don't have to know anything about them. If someone listens to the object, then he takes care of it.

If it was one to one relation and the object waiting for something to happen is always of the same type, then you wouldn't really need an event for that case.

Events are also great to decouple systems, like seen in my example above with the weather station. The weather station can run on its own without knowing about the services or users that are listening to it.

Upvotes: 5

Martin Liversage
Martin Liversage

Reputation: 106956

Using events will among other things:

  • Decouple the event source from the event receiver
  • Allow multiple event receivers to subscribe to the same event
  • Provide a well known pattern for implementing eventing

One thing to be aware of is how delegates may create unexpected "leaks" in your code: Memory Leak in C#.

Upvotes: 3

Related Questions