wpf 在视图模型的构造函数中调用异步方法加载数据有警告

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24572064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 12:05:06  来源:igfitidea点击:

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

c#.netwpfasynchronousasync-await

提问by Allen4Tech

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.

我的视图包含一个 ListView,它显示来自 Internet 的一些数据,我创建了一个异步方法来加载数据并在我的视图模型的构造函数中调用该方法。它有一个警告提示我现在使用 await 关键字。

Any other solution to load data asynchronously in the constructor?

在构造函数中异步加载数据的任何其他解决方案?

回答by Yuval Itzchakov

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

有几种模式可以应用,Stephan Cleary 在帖子中提到了所有模式。

However, let me propose something a bit different:

但是,让我提出一些不同的建议:

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

由于您在 WPF 应用程序中,我将使用该FrameworkElement.Loaded事件并将其绑定到ICommand您的 ViewModel 内部。有界命令将是Awaitable DelegateCommand可以等待的。我也会利用System.Windows.Interactivity.InvokeCommandAction

View XAML:

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

回答by Ananke

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.

就我个人而言,我会将数据的加载委托给一个方法,例如 Task LoadDataAsync(...) ...但是,如果您将异步方法的结果分配给一个字段,那么警告应该会消失。如果您正在调用 Wait() 那么您是否应该首先调用异步方法是有问题的。

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

有关您可能感兴趣的异步初始化模式,请参阅http://blog.stephencleary.com/2013/01/async-oop-2-constructors.html