Calling async method to load data in constructor of viewmodel has a warning Calling async method to load data in constructor of viewmodel has a warning wpf wpf

Calling async method to load data in constructor of viewmodel has a warning


There are a couple of patterns which can be applied, all mentioned in the post by Stephan Cleary.

However, let me propose something a bit different:

Since you are in a WPF application, i would use the FrameworkElement.Loaded event and bind it to a ICommand inside you ViewModel. The bounded command would be an Awaitable DelegateCommand which can be awaited. I'll also take advantage of System.Windows.Interactivity.InvokeCommandAction

View XAML:

<Grid> <interactivity:Interaction.Triggers>     <interactivity:EventTrigger EventName="Loaded">         <interactivity:InvokeCommandAction Command="{Binding MyCommand}"/>     </interactivity:EventTrigger> </interactivity:Interaction.Triggers></Grid>

ViewModel:

public class ViewModel{    public ICommand MyCommand { get; set; }    public ViewModel()    {        MyCommand = new AwaitableDelegateCommand(LoadDataAsync);    }    public async Task LoadDataAsync()    {        //await the loading of the listview here    }}


Personally I would delegate the loading of the data to a method e.g. Task LoadDataAsync(...) ...however if you assign the result of the async method to a field then the warning should go away. If you are calling Wait() then it is questionable whether you should be calling an async method in the first place.

See http://blog.stephencleary.com/2013/01/async-oop-2-constructors.html for an asynchronous initialization pattern that may be of interest to you.