Raising events safely in C Sharp (C#) - Time & Space Complexity
When raising events safely in C#, we want to know how the time to notify listeners grows as more listeners subscribe.
We ask: How does the number of event subscribers affect the time it takes to raise an event?
Analyze the time complexity of the following code snippet.
public event EventHandler? MyEvent;
public void RaiseEvent()
{
var handler = MyEvent;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
This code raises an event by calling all subscribed listeners safely using a local copy.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Invoking each subscribed event handler one by one.
- How many times: Once for each subscriber currently attached to the event.
When you have more subscribers, the event must call each one, so the work grows with the number of subscribers.
| Input Size (number of subscribers) | Approx. Operations (calls) |
|---|---|
| 10 | 10 calls |
| 100 | 100 calls |
| 1000 | 1000 calls |
Pattern observation: The number of calls grows directly with the number of subscribers.
Time Complexity: O(n)
This means the time to raise the event grows linearly with the number of subscribers.
[X] Wrong: "Raising an event always takes constant time regardless of subscribers."
[OK] Correct: Each subscriber is called in turn, so more subscribers mean more calls and more time.
Understanding how event raising scales helps you write responsive and efficient code when many listeners are involved.
What if we changed the event to raise handlers asynchronously? How would the time complexity change?