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

Event unsubscription and memory in C Sharp (C#) - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Event unsubscription and memory
Subscribe event handler
↓
Event raised
↓
Handler called
↓
Unsubscribe event handler
↓
Event raised again
↓
Handler NOT called
↓
Memory freed if no other refs
This flow shows subscribing an event handler, calling it when event fires, then unsubscribing so it no longer runs and memory can be freed.
Execution Sample
C Sharp (C#)
using System;

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

var pub = new Publisher();
void Handler() => Console.WriteLine("Called");
pub.OnChange += Handler;
pub.Raise();
pub.OnChange -= Handler;
pub.Raise();
This code subscribes a handler to an event, raises the event (handler runs), unsubscribes, then raises again (handler does not run).
Execution Table
StepActionEvent Handler ListOutput
1Create Publisher instanceempty
2Define Handler methodempty
3Subscribe Handler to OnChangeHandler
4Raise event (pub.Raise())HandlerCalled
5Unsubscribe Handler from OnChangeempty
6Raise event again (pub.Raise())empty
💡 Event handler list empty after unsubscription, so no output on second raise.
Variable Tracker
VariableStartAfter Step 3After Step 5Final
pub.OnChangenullHandlernullnull
Key Moments - 2 Insights
Why does the handler not run after unsubscription?
Because in step 5 the handler is removed from the event list, so at step 6 the event has no handlers to call (see execution_table rows 5 and 6).
How does unsubscription help with memory?
If the handler is not unsubscribed, the event publisher keeps a reference to it, preventing garbage collection. Unsubscribing removes this reference, allowing memory to be freed.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the event handler list after step 3?
Aempty
Bnull
CHandler
DMultiple handlers
💡 Hint
Check the 'Event Handler List' column at step 3 in execution_table.
At which step does the event handler get removed?
AStep 3
BStep 5
CStep 2
DStep 6
💡 Hint
Look at the 'Action' column in execution_table for when unsubscription happens.
If we did not unsubscribe the handler, what would happen at step 6?
AHandler runs again
BNo output
CError thrown
DEvent handler list becomes empty
💡 Hint
Refer to the output column at step 4 and consider what happens if handler remains subscribed.
Concept Snapshot
Event subscription adds handlers to a list.
Raising event calls all handlers.
Unsubscription removes handlers.
Without unsubscription, handlers stay referenced.
This can cause memory leaks.
Always unsubscribe to free memory.
Full Transcript
This example shows how subscribing an event handler adds it to the event's internal list. When the event is raised, all subscribed handlers run. Unsubscribing removes the handler from the list, so it no longer runs when the event fires. This also allows the handler to be garbage collected, preventing memory leaks. The execution table traces each step: creating the publisher, subscribing the handler, raising the event (handler runs), unsubscribing, and raising again (no handler runs). The variable tracker shows the event handler list changing from null to containing the handler and back to null. Key moments clarify why unsubscription stops the handler from running and why it is important for memory management. The quiz tests understanding of the event handler list state and effects of unsubscription.

Practice

(1/5)
1. What happens if you do not unsubscribe from an event in C#?
easy
A. The event will automatically unsubscribe after the first call.
B. The program will throw a compile-time error.
C. The subscriber object may not be garbage collected, causing a memory leak.
D. The event handler will be called only once.

Solution

  1. Step 1: Understand event subscription behavior

    When an object subscribes to an event, the event publisher holds a reference to the subscriber's method.
  2. Step 2: Effect of not unsubscribing

    If you don't unsubscribe, the subscriber object remains referenced and cannot be garbage collected, causing a memory leak.
  3. Final Answer:

    The subscriber object may not be garbage collected, causing a memory leak. -> Option C
  4. Quick Check:

    Not unsubscribing = memory leak [OK]
Hint: Always unsubscribe to avoid memory leaks and keep memory clean [OK]
Common Mistakes:
  • Assuming events auto-unsubscribe
  • Thinking unsubscribing causes errors
  • Believing event handlers run only once
2. Which syntax correctly unsubscribes a method named OnDataReceived from an event DataReceived?
easy
A. DataReceived -= OnDataReceived;
B. DataReceived += OnDataReceived;
C. DataReceived = null;
D. DataReceived.Unsubscribe(OnDataReceived);

Solution

  1. Step 1: Recall event unsubscription syntax

    In C#, to unsubscribe from an event, use the '-=' operator with the same method.
  2. Step 2: Match correct syntax

    DataReceived -= OnDataReceived; uses 'DataReceived -= OnDataReceived;', which is the correct way to unsubscribe.
  3. Final Answer:

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

    Unsubscribe syntax = '-=' operator [OK]
Hint: Use '-=' with the same method to unsubscribe events [OK]
Common Mistakes:
  • Using '+=' instead of '-=' to unsubscribe
  • Trying to assign null to the event
  • Using non-existent Unsubscribe method
3. What will be the output of the following code?
using System;
class Program {
  static event Action MyEvent;
  static void Handler() => Console.WriteLine("Called");
  static void Main() {
    MyEvent += Handler;
    MyEvent -= Handler;
    MyEvent?.Invoke();
  }
}
medium
A. Called
B. No output
C. NullReferenceException
D. Compile-time error

Solution

  1. Step 1: Analyze event subscription and unsubscription

    The method Handler is subscribed then immediately unsubscribed from MyEvent.
  2. Step 2: Check event invocation

    Since no handlers remain, MyEvent is null, so MyEvent?.Invoke() does nothing and prints no output.
  3. Final Answer:

    No output -> Option B
  4. Quick Check:

    Unsubscribed event = no call [OK]
Hint: Unsubscribed event handlers do not run when invoked [OK]
Common Mistakes:
  • Expecting output despite unsubscription
  • Ignoring null conditional operator
  • Thinking event throws exception if empty
4. Identify the problem in this code snippet related to event unsubscription:
class Publisher {
  public event Action OnChange;
  public void Raise() => OnChange?.Invoke();
}
class Subscriber {
  public void Subscribe(Publisher p) {
    p.OnChange += HandleChange;
  }
  void HandleChange() {
    Console.WriteLine("Changed");
  }
}
medium
A. Subscriber never unsubscribes, causing potential memory leaks.
B. Event is invoked incorrectly with null conditional operator.
C. Handler method signature does not match event delegate.
D. Publisher event is not declared as static.

Solution

  1. Step 1: Review subscription and unsubscription

    The Subscriber subscribes to the event but never unsubscribes.
  2. Step 2: Understand consequences

    Without unsubscription, the Subscriber object remains referenced by Publisher, causing memory leaks.
  3. Final Answer:

    Subscriber never unsubscribes, causing potential memory leaks. -> Option A
  4. Quick Check:

    Missing unsubscribe = memory leak risk [OK]
Hint: Always unsubscribe to avoid memory leaks in event handlers [OK]
Common Mistakes:
  • Ignoring unsubscription importance
  • Confusing static and instance events
  • Assuming null conditional operator causes errors
5. You have a long-running application where multiple subscribers attach to a static event but never unsubscribe. What is the best approach to prevent memory leaks?
hard
A. Replace events with polling loops to avoid subscription issues.
B. Make the event instance-level instead of static to avoid leaks.
C. Ignore unsubscription because garbage collector handles it automatically.
D. Use weak event patterns or explicitly unsubscribe when subscribers are no longer needed.

Solution

  1. Step 1: Understand static event references

    Static events hold references for the app lifetime, so subscribers never get garbage collected unless unsubscribed.
  2. Step 2: Best practice to avoid leaks

    Using weak event patterns or explicitly unsubscribing prevents memory leaks by releasing subscriber references.
  3. Final Answer:

    Use weak event patterns or explicitly unsubscribe when subscribers are no longer needed. -> Option D
  4. Quick Check:

    Weak events or unsubscribe = prevent leaks [OK]
Hint: Use weak events or unsubscribe explicitly to avoid leaks [OK]
Common Mistakes:
  • Assuming GC cleans static event subscribers
  • Changing event to instance-level without reason
  • Replacing events with inefficient polling
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