Hello @Kim Strasser ,
Try searching for these patterns across your entire solution:
-
AddObserver -
NSNotificationCenter -
AVPlayerViewController(video playback often creates internal observers) - Any custom renderers or handlers
- Third-party libraries that might use notification observers
You might also have observers created by MAUI/Xamarin.Forms controls themselves, especially if you’re working with media playback components.
Issue with your current code
There’s a problem with the disposal order:
observer = NSNotificationCenter.DefaultCenter.AddObserver(
new NSString("AVPlayerItemDidPlayToEndTimeNotification"), async (notification) =>
{
PlayerViewController.DismissViewController(true, null);
PlayerViewController.Player.Dispose();
PlayerViewController.Dispose();
NSNotificationCenter.DefaultCenter.RemoveObserver(observer);
});
You’re removing the observer with RemoveObserver, but you’re not calling observer.Dispose() on the observer object itself. Removing it from the notification center isn’t the same as disposing the NSObject wrapper.
Proper disposal pattern
You should implement this at the class level where your observer lives:
private NSObject observer;
// When setting up your observer
observer = NSNotificationCenter.DefaultCenter.AddObserver(
AVPlayerItem.DidPlayToEndTimeNotification,
HandleVideoEnd);
// In your cleanup code (like Dispose or view disappearing)
public void Dispose()
{
if (observer != null)
{
NSNotificationCenter.DefaultCenter.RemoveObserver(observer);
observer.Dispose(); // This is the critical part you’re missing
observer = null;
}
}
Will it crash in production?
Your app might not crash immediately, but you’re leaking memory. Each undisposed observer keeps objects in memory. Over time, especially if users navigate to views that create these observers repeatedly, memory usage will grow and could eventually cause crashes or performance issues.
Debugging steps
- Use Visual Studio’s memory profiler to track object allocations.
- Check if
AVPlayerViewControllerorAVPlayercreates internal observers that need explicit disposal. - Look for any custom renderers or platform-specific code that might create observers.
- Review any media playback libraries you’re using.
Hope this helps, and happy holidays.