C#C
C#3y ago
1 reply
Jochem

❔ MAUI Error when loading resources on loading page

I have a view that displays the Cards property as a CollectionView. The view model is populating the hand data member inside a asynchronous function. The problem is that with the code below, sometimes my program will crash on startup and sometimes it will not. When commenting out the single statement in my constructor, the program won't crash. I think there's something wrong with the way I load my resources. Is there a better approach for loading resources that are needed on a page load (using MVVM)?

public class GameViewModel : IGameViewModel 
{
  ...

  private readonly List<Card> hand = new();
  public IReadOnlyCollection<Card> Hand => hand.AsReadOnly();

  public GameViewModel(DeckOfCardsService service)
  {
     Task.Run(() => Task.FromResult(Initialize(service))).Wait();
  }
 
  private async Task Initialize(DeckOfCardsService service)
  {
      var deck = await service.GetDeckAsync(); // Makes a REST API request.
  
      for (int i = 0; i < 5; ++i)
      {
          hand.Add(deck.Draw());
      }
  
      OnPropertyChanged("Hand");
  }
}

The location where my IDE points me to when stopping the program.
#if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
            UnhandledException += (sender, e) =>
            {
                if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
            };
#endif
Was this page helpful?