Introduction to Events and Event- Handlers
In this post I will show you have to simplify communication between components using Events and Event-Handlers.
Join the DZone community and get the full member experience.
Join For FreeIntroduction
Our physical world is surrounded by events e.g. Door Opened, Engine Started, Plane landed, etc., and we see events in the virtual world as well e.g. email received, friend-request sent, post liked etc. This is a very common concept, All popular programming languages support this, and in this post we will see that how we can use events in .NET applications.
Similar to Events, which are raised from users on the UI (e.g. click Save button), the objects in our code can also raise events and then those events can be processed by some other objects. For demo purpose, I will be using .NET but you can use any programming language for the implementation.
Events are part of .NET Framework and can be used for notification purposes inside your code. I will suggest you to use this functionality as it will reduce coupling in your code.
There are a lot of articles available online about this functionality and sometimes those contain information about underlying infrastructure code e.g. delegates, multicast delegates, invocation list etc. Those are important concepts but if you are doing some basic notification, then you even don’t need to know about those details and this is what I am going to show you in this post.
The examples are very simple and that is the idea, keep this post simple and same time learn how we can use this built-in notification system in our code.
Defining an Event
Events can be defined in a class using event keyword.
public class Printer {
// event [delegate] [eventName]
public event EventHandler printed;
}
Here we are using built-in delegate (EventHandler) in the above example. So printed is an event, which this class will raise at some point and lets see a simple implementation of Printer class and notice that we are raising this printed event inside Print method.
Raising the Event
Events are raised by calling the event like a method. In the above shown Printer class, we Raise the printed event after checking for NULL.
Event Handler
Once, we raised the event, it shall be handled somewhere. For this purpose I created a Reporter class as follows:
The Report method is the handler for the previously raised event (printed event).
So, what happens when we raise the event and there is no event-handler? Well, ask yourself the question “Will there be a noise if there is no listener”? We will see what .NET has to say about this philosophical question in the upcoming section (unsubscribing events) in this post.
Wiring Event Publisher and Event Consumer
The += operator is used to attach an event to an event-handler. In our example, the Printer class is a publisher, it publishes an event (printed) and Reporter class is the consumer of that event.
Execution
Here is the result when I ran this code:
The last line shows the output from the Reporter object which we wired earlier in the code.
Adding Another Handler
Lets add another handler to our code and see how easy it is add multiple handlers of the event. I added a new Class class Logger and then wire it up as shown below:
and here is the output of the execution:
Unsubscribing Events
Usually, it's a good idea to unsubscribe from events once you are done with that part. It is not always needed. Basically, if you are sure that the subscribing object is going to outlive the event source, you ought to unsubscribe.
So if you don’t unsubscribe, your object might be kept alive by this reference, making effectively a memory leak. By unsubscribing you are removing that reference.
The following code demonstrate that:
and here is the output of executing code.
Notice that , when printer.Print() method is called second time (after unsubscribing event) the handler’s code didn’t execute.
Summary
This was a very basic introduction to .NET Events and EventHandlers. They are great construct built right into .NET and you can use them easily in your applications. Let me know if you have some comments or questions. Till next time, Happy Coding.
Published at DZone with permission of Jawad Hasan Shani. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Building a Flask Web Application With Docker: A Step-by-Step Guide
-
Building the World's Most Resilient To-Do List Application With Node.js, K8s, and Distributed SQL
-
Getting Started With Kubernetes-Native CI/CD Pipelines
-
Future of Software Development: Generative AI Augmenting Roles and Unlocking Co-Innovation
Comments