Events
The Problem
Events are mechanism by which to communicate between objects. In particular, one object acts as a publisher that sends an event, while the other other acts as a subscriber receiving the event.
The major benefit of events is it makes applications more loosely coupled.
Imagine we have a video encoder where we want to send an email after the encoding is complete. In normal cases, you will use dependency injection to insert services into your VideoEncoder
class:
This code is generally fine. However, the problem arises when we have to add another service:
Problem: Adding another service means that VideoEncoder
and all classes that inherit from or use VideoEncoder
must be recompiled! Additionally, if we mess up our new logic, it could break in every place where VideoEncoder
is used.
Setting Up a Publisher
To solve the above problem, we don't dependency inject anything into VideoEncoder
. It has no awareness of MailService
or MessageService
.
Instead, VideoEncoder
, as a publisher, just needs to do the following:
Define a delegate
Define an event based on that delegate
Raise the event
Things to note:
We use a delegate to set a contract between publisher and subscriber. You'll see later that the subscriber must adhere to the signature of the delegate.
The convention for a delegate used for an event is to name it
<EventName>EventHandler
.The convention for an event-raising method is to name it
On<EventName>
.The best practice for event-raising methods is to apply the access modifiers
protected
andvirtual
.
Setting Up a Subscriber
Now that we have a publisher set up, we need to make sure the MailService
and MessageService
classes subscribe to the event.
The process is exactly like storing methods in a delegate:
Define a method that matches the signature of the delegate
Add the method to the event
That's it! Now MailService
and MessageService
will work after the video finishes encoding.
Passing custom args to EventArgs
EventArgs
Suppose that we want our subscribers to get access to the video
that was just encoded. To do this, we need to expand on EventArgs
, so we can pass video
to the subscriber.
EventHandler
Delegate
EventHandler
DelegateInstead of defining our own custom VideoEncodedEventHandler
delegate, .NET framework now provides the built-in EventHandler
delegate.
EventHandler
is a delegate with a return type ofvoid
and parametersobject source
andEventArgs e
.EventHandler<TEventArgs>
is the same delegate except you pass your own custom event args.
Here's how the code looks:
Last updated