UWP, how to navigate from a page and close Monogame properly

I’m building UWP app on the Desktop that includes MonoGame rendering on some of the XAML pages. I have noticed that when I navigate from the page with MonoGame running, the memory doesn’t get properly disposed and grows larger and larger with subsequent loads to the page with the MonoGame graphics. In general the structure looks as follows:


// My game class
public class MyGame: Game
{
/// Methods for game class ...

/// Dispose method
protected override void Dispose(bool disposing)
        {
base.Dispose(disposing);
if (Content != null)
            {
                Content.Unload();
                Content.Dispose();
            }
}

}

// Calling in Page_Unloaded() of the XAML/cs class that has a SwapChainPannel as the rendering surface

public sealed partial class MonoPage: Page
{
// member declarations etc.

MyGame _game;

public MonoPage()
{

// initializations....
           _game = MonoGame.Framework.XamlGame<SkeletonViewer>.Create(launchArguments, Window.Current.CoreWindow, swapChainPanel);
 
}

private void Page_Unloaded(object sender, RoutedEventArgs e)
        {
_game.Dispose();
}

}

In my understanding, the Page_Unloaded is called when all the graphics elements are not visible anymore. However, the navigation process from this page throws an exception after a new page is loaded into the frame:

System.NullReferenceException: ‘Object reference not set to an instance of an object.’

MonoGame.Framework.dll!Microsoft.Xna.Framework.UAPGameWindow.Window_FocusChanged(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.WindowActivatedEventArgs args)	Unknown

It seems that the MonoGame rendering process is still active after navigating to a new page and fails due to null pointer created by the base.Dispose() of MyGame object. Is there a way to properly stop the MonoGame object inside the application and clean up (without calling Exit)?

1 Like

yes
after uwp page navigation the game is still running
monogame v3.8
searching a solution for this too