Question

I am using the MVVMLight framework in a metro app. I began by loading data in my ViewModel constructors and everything worked fine. Towards the end of the build I introduced some extra exception handling in the app.xaml.

TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;

This began to throw a lot of errors about tasks not being awaited properly.

I moved the ViewModel constructor data load calls into my page LoadState method and awaited them there and all works fine. However, I have read that this is possibly bad practice.

Should I introduce an async call to the ViewModel constructor somehow instead? Interested what best pratice may be? Maybe I should remove the exception handler!

A similar question has been asked here: MVVM view model and async data initialisation

Was it helpful?

Solution

Not sure where you saw that Data call load in LoadState would be a bad practice, in most case you would not even be able to load the data before load state since you would need whatever parameter is passed by LoadState. Also even of the parameter is not needed I personally prefer to load data in LoadState because starting loading it in the constructor mean that you are going to take some of the cpu time while the page is loading so it will take the page a little longer to load. The only reason I see to load it in the constructor would be so that the data is loaded at design time (because the view model cosntructor will be called but not LoadState) but for that you can just add a condition (ViewModelBase.IsInDesignModeStatic) to call load in the constructor for design time

OTHER TIPS

First, a couple of rules:

  1. Ensure that all Tasks are awaited
  2. Never write async void except for event handlers.

That taken care of, check if you still have some errors. Chances are you already had some errors but they haven't surfaced.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top