WinRT async data load in constructor

后端 未结 2 1935
暗喜
暗喜 2020-12-31 18:53

I want to load some data in the constructor of a ViewModel but due to WinRT\'s async nature I am forced to use async methods. Unfortunately I cannot have an async constructo

2条回答
  •  旧时难觅i
    2020-12-31 19:10

    Forcing async methods to run synchronously usually leads to deadlocks, so I would not recommend that. The thing with view models is that they usually support change notifications through INotifyPropertyChanged PropertyChanged event, so there is no need to have all data available immediately. In fact if your data isn't hard-coded - you shouldn't expect to see the data immediately and you would most likely want to show a progress indicator while the data is loading. Thus...

    In your constructor call an async initialization method without awaiting the result (since you can't await in a constructor) and in the initialization method when all data is available - assign it to property/properties that your view binds to, raise PropertyChanged event for these properties and hide the progress indicator by changing the view model property that controls its visibility.

提交回复
热议问题