Bird
Raised Fist0
C Sharp (C#)programming~10 mins

Publisher-subscriber execution model in C Sharp (C#) - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Publisher-subscriber execution model
Publisher creates event
↓
Subscribers register handlers
↓
Publisher triggers event
↓
All subscribers receive notification
↓
Subscribers execute their handlers
↓
Event handling complete
The publisher creates an event and subscribers register their handlers. When the publisher triggers the event, all subscribers get notified and run their handlers.
Execution Sample
C Sharp (C#)
using System;

class Publisher {
  public event Action OnChange;
  public void Notify() => OnChange?.Invoke();
}

class Subscriber {
  public void Respond() => Console.WriteLine("Subscriber notified");
}

var pub = new Publisher();
var sub = new Subscriber();
pub.OnChange += sub.Respond;
pub.Notify();
This code shows a publisher with an event and a subscriber that registers a handler. When the publisher notifies, the subscriber prints a message.
Execution Table
StepActionEvent StateSubscribers RegisteredOutput
1Create Publisher instanceNo event triggeredNone
2Create Subscriber instanceNo event triggeredNone
3Subscriber registers Respond handlerNo event triggeredRespond handler added
4Publisher calls Notify()Event triggeredRespond handler addedSubscriber notified
5Event handling completeNo event triggeredRespond handler remains
💡 Notify() finished, all subscribers notified
Variable Tracker
VariableStartAfter Step 3After Step 4Final
pub.OnChangenullRespond handler addedRespond handler addedRespond handler added
subnullSubscriber instanceSubscriber instanceSubscriber instance
Key Moments - 3 Insights
Why does the event call use OnChange?.Invoke() instead of just OnChange()?
The ?. operator checks if any subscribers are registered before calling Invoke. This prevents errors if no handlers exist, as shown in step 4 of the execution_table.
What happens if multiple subscribers register to the same event?
All registered handlers are called in order when the event triggers. The execution_table shows one subscriber, but more would be called similarly.
Does the event keep subscribers after Notify() is called?
Yes, subscribers remain registered until explicitly removed. Step 5 shows the handler still registered after Notify().
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the state of pub.OnChange after step 3?
ARespond handler added
Bnull (no handlers)
CEvent triggered
DEmpty delegate
💡 Hint
Check the 'Event State' and 'Subscribers Registered' columns at step 3
At which step does the subscriber print 'Subscriber notified'?
AStep 2
BStep 4
CStep 3
DStep 5
💡 Hint
Look at the 'Output' column in the execution_table
If no subscriber registers, what happens when Notify() is called?
ANullReferenceException error
BEvent triggers but no output
CNothing happens, safely ignored
DProgram crashes
💡 Hint
Refer to the use of ?.Invoke() in the code and step 4 explanation
Concept Snapshot
Publisher-subscriber model:
- Publisher defines event (e.g., event Action OnChange)
- Subscribers register handlers (+=)
- Publisher triggers event (Invoke())
- All subscribers notified in order
- Use ?.Invoke() to avoid errors if no subscribers
Full Transcript
The publisher-subscriber execution model involves a publisher that creates an event and subscribers that register their handlers to this event. When the publisher triggers the event by calling Invoke, all registered subscribers receive the notification and execute their handlers. The ?.Invoke() syntax ensures safe calling even if no subscribers are registered. Subscribers remain registered until removed. This model allows decoupled communication where publishers do not need to know about subscribers directly.

Practice

(1/5)
1. In the publisher-subscriber model in C#, what is the main role of the subscriber?
easy
A. To send messages to multiple listeners
B. To register methods that respond to events from the publisher
C. To create new events for the publisher
D. To directly modify the publisher's data

Solution

  1. Step 1: Understand the roles in the model

    The publisher sends messages or events, while the subscriber listens and reacts.
  2. Step 2: Identify subscriber's responsibility

    Subscribers register their methods to handle events raised by the publisher.
  3. Final Answer:

    To register methods that respond to events from the publisher -> Option B
  4. Quick Check:

    Subscriber = method registration [OK]
Hint: Subscribers listen and react by registering methods [OK]
Common Mistakes:
  • Confusing publisher and subscriber roles
  • Thinking subscriber sends messages
  • Assuming subscriber modifies publisher directly
2. Which of the following is the correct syntax to subscribe a method named OnDataReceived to an event DataReceived in C#?
easy
A. DataReceived += OnDataReceived;
B. DataReceived = OnDataReceived();
C. DataReceived -= OnDataReceived;
D. OnDataReceived += DataReceived;

Solution

  1. Step 1: Recall event subscription syntax

    In C#, subscribing to an event uses the += operator with the method name (without parentheses).
  2. Step 2: Match correct syntax

    DataReceived += OnDataReceived; correctly subscribes the method.
  3. Final Answer:

    DataReceived += OnDataReceived; -> Option A
  4. Quick Check:

    Subscribe event = += method [OK]
Hint: Use += to subscribe methods to events [OK]
Common Mistakes:
  • Using = instead of +=
  • Calling method with parentheses when subscribing
  • Confusing subscription with unsubscription (-=)
3. Consider the following C# code snippet:
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?
medium
A. No output
B. NullReferenceException
C. Event received
D. Compile-time error

Solution

  1. 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.
  2. Step 2: Analyze output of Respond method

    Respond prints "Event received" to the console, so this text will appear.
  3. Final Answer:

    Event received -> Option C
  4. Quick Check:

    Subscribed method runs and prints message [OK]
Hint: Subscribed methods run on event invoke [OK]
Common Mistakes:
  • Forgetting to subscribe the method
  • Expecting no output if event is null
  • Confusing event invocation syntax
4. The following code tries to unsubscribe a method from an event but causes a runtime error:
public class Publisher {
    public event Action Notify;
}

var pub = new Publisher();
pub.Notify -= () => Console.WriteLine("Hello");

What is the main issue causing the error?
medium
A. Lambda expressions cannot be used with events
B. Events cannot be unsubscribed in C#
C. The event Notify is not initialized
D. Cannot unsubscribe a lambda expression that was never subscribed

Solution

  1. Step 1: Understand event unsubscription rules

    In C#, events start as null delegates. Unsubscribing (-=) from a null event throws NullReferenceException.
  2. 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.
  3. Final Answer:

    Cannot unsubscribe a lambda expression that was never subscribed -> Option D
  4. Quick Check:

    Null event -= throws NullRef [OK]
Hint: Unsubscribe only delegates you subscribed before [OK]
Common Mistakes:
  • Assuming unsubscribing any lambda works
  • Thinking events cannot be unsubscribed
  • Confusing null event invocation with unsubscription
5. You want to implement a publisher-subscriber system where multiple subscribers can register to receive messages, but some subscribers should only receive messages if a condition is true (e.g., message contains a keyword). Which approach best applies this conditional filtering in C#?
hard
A. Use event subscription with wrapper methods that check the condition before handling
B. Modify the publisher to send messages only to specific subscribers directly
C. Use multiple events for each condition and subscribe accordingly
D. Use a single event and let subscribers unsubscribe if condition is false

Solution

  1. Step 1: Understand conditional filtering in subscriber model

    The publisher sends events to all subscribers; filtering is best done in subscriber methods.
  2. Step 2: Apply wrapper methods for condition

    Subscribers can register methods that first check the condition and only proceed if true, keeping publisher simple.
  3. Step 3: Evaluate other options

    Modifying publisher to target subscribers breaks decoupling; multiple events add complexity; unsubscribing dynamically is inefficient.
  4. Final Answer:

    Use event subscription with wrapper methods that check the condition before handling -> Option A
  5. Quick Check:

    Filter in subscriber methods for flexibility [OK]
Hint: Filter messages inside subscriber methods [OK]
Common Mistakes:
  • Trying to filter inside publisher breaking decoupling
  • Creating many events for each condition
  • Unsubscribing subscribers dynamically instead of filtering
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard