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

落爺英雄遲暮 提交于 2019-12-20 09:56:13

问题


My view contains a ListView which display some data from internet, I create an async method to load data and call the method in my viewmodel's constructor. It has an warning prompt me now use await keyword.

Any other solution to load data asynchronously in the constructor?


回答1:


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
    }
}



回答2:


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.




回答3:


Don't use the constructor to do that. You can use the event Window Loaded to do that.

This is a little example:

public YourWindow()
{
    InitializeComponent();
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    // Your code here ...
    // If you want use async, use the keyword async in the event method.
    // private async void Window_Loaded(object sender, RoutedEventArgs e)
}

Remember to add the event in the XAML:

<Title="YourWindow" ... Loaded="Window_Loaded">


来源:https://stackoverflow.com/questions/24572064/calling-async-method-to-load-data-in-constructor-of-viewmodel-has-a-warning

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!