Events
- A mechanism for communication between objects
- Used in building
Loosely Coupled Applications
- Helps extending applications
Example
1 | public class VideoEncoder{ |
but, in the future, if we want to send text message to the video owner.
1 | public class VideoEncoder{ |
but if we do it this way, the whole Encode() method will need to be recompiled, and the class depends on this function, will need to be recompiled and redeploied.
We want to design our application such that when you want to change that, it changes the minimum impact on the application
We can use Event
to deal with this problem.
How we do event in this case
- VideoEncoder
- publisher
- event sender
- MailService
- Subscriber
- event receiver
So, in future.
- MessageService
- Subscriber
- event receiver
Main changes
1 | public class VideoEncoder{ |
OnVidoEncoded()
method simply notify the subscribers.
VideoEncoder knows absoulately nothing about the MailService and MessageService or any other subscribers.
They(subscribers) can come later, and we can add more subscribers.
One Question Raise: How VideoEncoder(publisher) notify its subscribers
We need an agreement or contract between publisher and its subscribers.
1 | public void OnVideoEncoded(object source, EventArgs e){ |
This is a very typical implementation of method in the subscribers
, and it is called EventHandler
.
This is also the method which called by the publisher when the event is raised.
Again, VideoEncoder(Event Publisher) do not know the existence of its publishers. Publisher decoupled from them(subscribers).
All the publisher knows, is a method(EventHandler).
How do you tell VideoEncoder(Publisher) what method to call?
That’s where a Delegate
comes in.
Delegates
- Agreement/ Contract between Publisher and Subscriber
- Determines the signature of the event handler method in Subscriber
- Define a delegate
- Define an event based on that delegate
- Raise the event
1 | public delegate void VideoEncodedEventHandler(object source, EventArgs args); |
object source
: source of that eventEventArgs args
: any additional data we want to send to the event
Here we declare an event, which hold a reference to a function, look like
1 | void VideoEncodedEventHandler(object source, EventArgs args); |
Implementation
Program.cs
1 | namespace EventsAndDelegates |
Video.cs
1 | namespace EventsAndDelegates |
VideoEncoder.cs
1 | using System; |
MailService.cs
1 | using System; |
MessageService.cs
1 | using System; |