0
0
C Sharp (C#)programming~7 mins

Publisher-subscriber execution model in C Sharp (C#)

Choose your learning style9 modes available
Introduction

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.

When you want one part of your program to send messages to many other parts without knowing who they are.
When you want to react to events like button clicks, data updates, or messages from other systems.
When you want to keep your code organized by separating who sends information and who listens.
When building apps that need to update many things at once after an action happens.
When you want to add new features without changing the existing code that sends messages.
Syntax
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.

Examples
If no one subscribes, sending a message does nothing.
C Sharp (C#)
// Example: No subscribers
Publisher publisher = new Publisher();
publisher.SendMessage("Hello"); // No output because no one listens
One subscriber listens and prints the message.
C Sharp (C#)
// Example: One subscriber
Publisher publisher = new Publisher();
Subscriber subscriber = new Subscriber("Alice");
publisher.MessageReceived += subscriber.OnMessageReceived;
publisher.SendMessage("Hello Alice");
Multiple subscribers get the message and each prints it.
C Sharp (C#)
// 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");
After unsubscribing, the subscriber no longer receives messages.
C Sharp (C#)
// 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");
Sample Program

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.

C Sharp (C#)
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.");
    }
}
OutputSuccess
Important Notes

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.

Summary

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.