从构造函数或属性运行异步方法 [英] Running async methods from contructor or propertys

查看:60
本文介绍了从构造函数或属性运行异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MVVM和WPF,现在我从viewmodel类的构造函数中调用异步过程,如下所示: Task.Run(()=> this.MyMetho(someParam)).Wait(); 问题在于屏幕将其冻结,直到任务结束.

I am using MVVM and WPF, now I am calling async process from my viewmodel class's constructor like this: Task.Run(() => this.MyMetho(someParam)).Wait(); The problem with this is that screen freeze it until the task ends.

另一种方法是在ViewModel中创建一个 LoadDataMethod ,并在事件处理程序的视图中为 UserControl_Loaded 调用它

Another way is to create a LoadDataMethod in the ViewModel and call it from the view in the event handler for UserControl_Loaded something like this

private async void UserControl_Loaded(object sender, RoutedEventArgs e)
{
    VMRep vm = (VMRep)this.DataContext;
    await vm.LoadDataMethod();
}

这种方法效果更好,但是我想有一种更好的方法来为View加载异步数据.

that way works better, but I guess there is a better way to do the load of async data for a View.

感谢您的评论

推荐答案

好吧,由于我不知道您到底要完成什么,我正在尽力为您简要介绍懒惰

Well, since I don't know exactly what you're trying to accomplish I'm trying my best to give you a brief explanation about Lazy

   private Lazy<Task<string>> getInfo;

在这种情况下,我将使用 Lazy< Task< string>> 保存一个字段,在您的情况下,它将是 Lazy< Task< VMRep>> .我正在使用此字段,以便您可以在班级中调用此懒惰的Initialzier.

In this case I'm holding a field with Lazy<Task<string>> in your case it would be Lazy<Task<VMRep>>. I'm using this field, so that you can call this lazy initialzier inside your class.

   public Laziness()
   {
     this.getInfo = new Lazy<Task<string>>(async () => await this.GetInfo());
   }

在构造函数中,我将值分配给惰性字段.在这种情况下,使用方法 GetInfo()

In the constructor I'm assigning the value to the lazy field. In this case with the method GetInfo()

   public string GetLazyInfo
   {
     get
     {
        return this.getInfo.Value.Result;
     }
   }

使用公共属性公开 getInfo 字段.然后从懒惰任务中返回结果.

Exposing the getInfo field with a public property. And returning the result from the task inside the lazy.

   private async Task<string> GetInfo()
   {
     await Task.Run(async () => await Task.Delay(5000));
     return await Task.Run(() => "test");
   }

最后是可以发生魔术的方法.

And finally the method, where your magic can happen.

这篇关于从构造函数或属性运行异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆