Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to subscribe to an Event in C# and can we have multiple subscribers to one Event in a C#?
Events enable a class or object to notify other classes or objects when something of interest occurs. The class that raises the event is called the publisher and the classes that handle the event are called subscribers.
An event can have multiple subscribers, and a subscriber can handle multiple events from multiple publishers. Events that have no subscribers are never raised. The publisher determines when an event is raised; the subscribers determine what action is taken in response to the event.
Syntax
Following is the syntax for declaring an event using EventHandler −
public event EventHandler<EventArgsType> EventName;
Following is the syntax for subscribing to an event using the += operator −
publisher.EventName += subscriber.EventHandlerMethod;
Following is the syntax for unsubscribing from an event using the -= operator −
publisher.EventName -= subscriber.EventHandlerMethod;
How Events Work
Example with Multiple Subscribers
The following example demonstrates how multiple subscribers can listen to a single event −
using System;
using System.Threading;
class Program {
static void Main() {
var video = new MP4() { Title = "Eminem" };
var videoEncoder = new MP4EncoderNew();
var mailService = new MailService();
var messageService = new MessageService();
// Subscribe multiple services to the same event
videoEncoder.mp4Encoded += mailService.onVideoEncoded;
videoEncoder.mp4Encoded += messageService.onVideoEncoded;
videoEncoder.Encode(video);
}
}
public class MP4 {
public string Title { get; set; }
}
public class MP4Args : EventArgs {
public MP4 mp4 { get; set; }
}
public class MP4EncoderNew {
public event EventHandler<MP4Args> mp4Encoded;
public void Encode(MP4 video) {
Console.WriteLine("Encoding MP4");
Thread.Sleep(1000); // Simulate encoding time
OnVideoEncoded(video);
}
protected void OnVideoEncoded(MP4 video) {
if (mp4Encoded != null) {
mp4Encoded(this, new MP4Args() { mp4 = video });
}
}
}
// Subscriber 1
public class MailService {
public void onVideoEncoded(object source, MP4Args e) {
Console.WriteLine("Mail Service: Sending an email for {0}", e.mp4.Title);
}
}
// Subscriber 2
public class MessageService {
public void onVideoEncoded(object source, MP4Args e) {
Console.WriteLine("Message Service: Sending a message for {0}", e.mp4.Title);
}
}
The output of the above code is −
Encoding MP4 Mail Service: Sending an email for Eminem Message Service: Sending a message for Eminem
Adding and Removing Subscribers
You can dynamically add and remove event subscribers using the += and -= operators −
using System;
public class Publisher {
public event EventHandler<string> MyEvent;
public void TriggerEvent(string message) {
MyEvent?.Invoke(this, message);
}
}
public class Subscriber {
public string Name { get; set; }
public void HandleEvent(object sender, string message) {
Console.WriteLine($"{Name} received: {message}");
}
}
class Program {
static void Main() {
Publisher pub = new Publisher();
Subscriber sub1 = new Subscriber { Name = "Subscriber1" };
Subscriber sub2 = new Subscriber { Name = "Subscriber2" };
// Add subscribers
pub.MyEvent += sub1.HandleEvent;
pub.MyEvent += sub2.HandleEvent;
pub.TriggerEvent("Hello World!");
Console.WriteLine("\nRemoving Subscriber1...<br>");
// Remove a subscriber
pub.MyEvent -= sub1.HandleEvent;
pub.TriggerEvent("Second Message");
}
}
The output of the above code is −
Subscriber1 received: Hello World! Subscriber2 received: Hello World! Removing Subscriber1... Subscriber2 received: Second Message
Key Rules
-
Use the
+=operator to subscribe to an event. -
Use the
-=operator to unsubscribe from an event. -
Multiple subscribers can listen to the same event.
-
Events are called in the order subscribers were added.
-
Use the
eventkeyword to ensure encapsulation and prevent direct assignment.
Conclusion
Events in C# support multiple subscribers through the += operator, allowing one publisher to notify many subscribers simultaneously. This publisher-subscriber pattern enables loose coupling between classes and provides a flexible way to handle notifications when specific actions occur.
