The publisher-subscriber model helps different parts of a program talk to each other without being tightly connected. It makes programs easier to change and grow.
Publisher-subscriber execution model in C Sharp (C#)
using System; // Define a delegate for the event public delegate void MessageReceivedHandler(string message); // Publisher class public class Publisher { // Event based on the delegate public event MessageReceivedHandler MessageReceived; // Method to send message to subscribers public void SendMessage(string message) { MessageReceived?.Invoke(message); } } // Subscriber class public class Subscriber { private string subscriberName; public Subscriber(string name) { subscriberName = name; } // Method to handle the event public void OnMessageReceived(string message) { Console.WriteLine($"{subscriberName} received: {message}"); } }
The event keyword creates a special kind of delegate that only the publisher can invoke.
Subscribers add their methods to the event to listen for messages.
// Example: No subscribers Publisher publisher = new Publisher(); publisher.SendMessage("Hello"); // No output because no one listens
// Example: One subscriber Publisher publisher = new Publisher(); Subscriber subscriber = new Subscriber("Alice"); publisher.MessageReceived += subscriber.OnMessageReceived; publisher.SendMessage("Hello Alice");
// Example: Multiple subscribers Publisher publisher = new Publisher(); Subscriber alice = new Subscriber("Alice"); Subscriber bob = new Subscriber("Bob"); publisher.MessageReceived += alice.OnMessageReceived; publisher.MessageReceived += bob.OnMessageReceived; publisher.SendMessage("Hello everyone");
// Example: Unsubscribe Publisher publisher = new Publisher(); Subscriber alice = new Subscriber("Alice"); publisher.MessageReceived += alice.OnMessageReceived; publisher.SendMessage("First message"); publisher.MessageReceived -= alice.OnMessageReceived; publisher.SendMessage("Second message");
This program shows a publisher sending messages to two subscribers. Both receive the first message. Then Bob unsubscribes and only Alice receives the second message.
using System; public delegate void MessageReceivedHandler(string message); public class Publisher { public event MessageReceivedHandler MessageReceived; public void SendMessage(string message) { Console.WriteLine($"Publisher sends: {message}"); MessageReceived?.Invoke(message); } } public class Subscriber { private string subscriberName; public Subscriber(string name) { subscriberName = name; } public void OnMessageReceived(string message) { Console.WriteLine($"{subscriberName} received: {message}"); } } public class Program { public static void Main() { Publisher newsPublisher = new Publisher(); Subscriber alice = new Subscriber("Alice"); Subscriber bob = new Subscriber("Bob"); // Subscribers subscribe to the publisher's event newsPublisher.MessageReceived += alice.OnMessageReceived; newsPublisher.MessageReceived += bob.OnMessageReceived; Console.WriteLine("-- Sending first message --"); newsPublisher.SendMessage("Breaking news: Publisher-subscriber model works!"); // Bob unsubscribes newsPublisher.MessageReceived -= bob.OnMessageReceived; Console.WriteLine("-- Sending second message --"); newsPublisher.SendMessage("Update: Bob has unsubscribed."); } }
Time complexity: Sending a message calls all subscriber methods, so it is O(n) where n is the number of subscribers.
Space complexity: Storing subscribers uses O(n) space.
Common mistake: Forgetting to unsubscribe can cause memory leaks or unexpected behavior.
Use this model when you want loose coupling between parts of your program.
The publisher-subscriber model lets one part send messages to many listeners without knowing them.
Subscribers register methods to receive messages and can unsubscribe when needed.
This model helps keep code organized and flexible for changes.
Practice
Solution
Step 1: Understand the roles in the model
The publisher sends messages or events, while the subscriber listens and reacts.Step 2: Identify subscriber's responsibility
Subscribers register their methods to handle events raised by the publisher.Final Answer:
To register methods that respond to events from the publisher -> Option BQuick Check:
Subscriber = method registration [OK]
- Confusing publisher and subscriber roles
- Thinking subscriber sends messages
- Assuming subscriber modifies publisher directly
OnDataReceived to an event DataReceived in C#?Solution
Step 1: Recall event subscription syntax
In C#, subscribing to an event uses the += operator with the method name (without parentheses).Step 2: Match correct syntax
DataReceived += OnDataReceived; correctly subscribes the method.Final Answer:
DataReceived += OnDataReceived; -> Option AQuick Check:
Subscribe event = += method [OK]
- Using = instead of +=
- Calling method with parentheses when subscribing
- Confusing subscription with unsubscription (-=)
public class Publisher {
public event Action Notify;
public void Raise() {
Notify?.Invoke();
}
}
public class Subscriber {
public void Respond() {
Console.WriteLine("Event received");
}
}
var pub = new Publisher();
var sub = new Subscriber();
pub.Notify += sub.Respond;
pub.Raise();What will be the output when
pub.Raise() is called?Solution
Step 1: Understand event subscription and invocation
The subscriber's Respond method is subscribed to the Notify event, so it will be called when Raise() invokes Notify.Step 2: Analyze output of Respond method
Respond prints "Event received" to the console, so this text will appear.Final Answer:
Event received -> Option CQuick Check:
Subscribed method runs and prints message [OK]
- Forgetting to subscribe the method
- Expecting no output if event is null
- Confusing event invocation syntax
public class Publisher {
public event Action Notify;
}
var pub = new Publisher();
pub.Notify -= () => Console.WriteLine("Hello");What is the main issue causing the error?
Solution
Step 1: Understand event unsubscription rules
In C#, events start as null delegates. Unsubscribing (-=) from a null event throws NullReferenceException.Step 2: Identify cause of runtime error
No prior subscription means Notify is null, so pub.Notify -= lambda throws NullReferenceException. The lambda was never subscribed.Final Answer:
Cannot unsubscribe a lambda expression that was never subscribed -> Option DQuick Check:
Null event -= throws NullRef [OK]
- Assuming unsubscribing any lambda works
- Thinking events cannot be unsubscribed
- Confusing null event invocation with unsubscription
Solution
Step 1: Understand conditional filtering in subscriber model
The publisher sends events to all subscribers; filtering is best done in subscriber methods.Step 2: Apply wrapper methods for condition
Subscribers can register methods that first check the condition and only proceed if true, keeping publisher simple.Step 3: Evaluate other options
Modifying publisher to target subscribers breaks decoupling; multiple events add complexity; unsubscribing dynamically is inefficient.Final Answer:
Use event subscription with wrapper methods that check the condition before handling -> Option AQuick Check:
Filter in subscriber methods for flexibility [OK]
- Trying to filter inside publisher breaking decoupling
- Creating many events for each condition
- Unsubscribing subscribers dynamically instead of filtering
Ready to prove it?
Pass the test and this pattern moves unknown
