C# and .NET • Modern C# baseline
Events and Publisher-Subscriber Design
Notify subscribers without exposing the publisher’s event invocation mechanism.
An event is built around a delegate but restricts external code to subscribing and unsubscribing; only the publisher raises it. Long-lived publishers can keep subscribers alive through event references, so unsubscribe or use lifecycle-aware patterns when appropriate.
Key points
- Use EventHandler or EventHandler<TEventArgs> for conventional .NET events.
- Avoid invoking callbacks while holding locks unless the contract requires it.
Example
class DownloadProgress
{
public event EventHandler<int>? ProgressChanged;
public void Report(int percent)
{
ProgressChanged?.Invoke(this, percent);
}
}
What to expect
Subscribers are notified when Report is called; no event handler is required.
Practice exercise
Subscribe a handler, report two progress values, then unsubscribe and verify the final report is not received.
Key idea: Events decouple notification, but subscription lifetime still needs an owner.