Skip to main content

Practice ยท 4 of 4

Debug: The Bus That Never Lets Go

CHALLENGE
Difficulty: intermediate+25 XP

This EventBus leaks: subscribers it has "forgotten" still fire, and counts drift. Diagnose and write a correct version. Provided (broken) shape โ€” the bug is that Unsubscribe does nothing: ``csharp public sealed class EventBus // BROKEN โ€” do not ship this { public event EventHandler<string>? Ping; public void Unsubscribe(EventHandler<string> h) { /* silently does nothing */ } public void PingAll(string msg) => Ping?.Invoke(this, msg); } ` Write a correct EventBus: Subscribe returns the handler for later unsubscribing, Unsubscribe actually detaches, PingAll invokes current subscribers in subscription order. `csharp public static class Solution { public sealed class EventBus { public void Subscribe(EventHandler<string> h); public void Unsubscribe(EventHandler<string> h); public void PingAll(string msg); public int FiredCount; // total handler invocations } } ``

Back to lesson: Practice: Patterns Practice: Strategy, Decorator, Builder