[Critical error] UWP Initializes several times results in crash

I developed a game for several platforms with MonoGame. With the universal windows project I ran into a huge issue. The application gets initialized several times!

I did not recognize this before publishing the application, because this only happens with the release build mode, and I hadn’t tested it in this mode because of long build time. I had made sure that the application did work properly with debug mode on both my own devices as well as on emulators, however when I downloaded it from the store the app crashed on startup so I decided to start analyzing.

I finally built it in release mode and debugged it and placed several breakpoints in both App.xaml.cs and GamePage.xaml.cs. I noticed that these breakpoints got hit in an illogical order, jumping back and forth, even skipping lines of code. Even static boolean values got ignored etc.

I was able to recreate this with a blank project. How to:

  1. Create a new MonoGame Windows 10 Universal Project
  2. Set breakpoints in both App.xaml.cs and GamePage.xaml.cs, place them at practically each line
  3. Build first with debug mode, so that you get something to compare to
  4. Build in release mode, breakpoints should now be hit in a different order

The strange thing is that this only happens with the release build, not with the debug. A quick fix would be appreciated! Thanks in advance! :smiley:

EDIT: After more testing I noticed that this issue is not limited to MonoGame. Blank App Windows Universal projects do also have the same problem. This is also recreatable:

  1. Create new Blank App Windows Universal
  2. In the MainPage.xaml.cs create a new method that takes some time to complete. Call it in the MainPage constructor. My method (I know that it isn’t a method that should be used to measure performance, but it did the trick anyways):

Random random=new Random();
public void GGG()
----{
--------while (true)
--------{
------------if (random.Next(100000) == 100)
----------------break;
---------}
} (didn’t get the indentation to work)

  1. Place breakpoints in both App.xaml.cs and GamePage.xaml.cs
  2. Test in debug mode
  3. Test in release mode

The debug runs only once, when the release mode calls the method several times.

I do not know how to bypass this, but perhaps by moving the XamlGame.Create to after the page has been truly navigated to (after Windows.Current.Activate in App.xaml.cs). This does not truly bypass the problem, but because even if the initialization gets called several times, it evades the heaviest code.

I also decided to post the issue to StackOverflow, because this is not a MonoGame specific issue.