MVVM C#如何将异步数据加载到属性中? [英] MVVM c# how to load async data into a property?

查看:66
本文介绍了MVVM C#如何将异步数据加载到属性中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有更好的方法将异步数据加载到属性中.现在,我创建一个异步函数,并在属性的Get部分中引发一个Task,如下所示:

I wonder if there's a better approach to load async data into a property. now I create an async function and raise a Task in the Get part of the property like this:

private ObservableCollection<CProyecto> prope;

public ObservableCollection<CProyecto> Prope
{
    get 
    {
        if (prope == null)
        {
            Task.Run(()=> LoadData()).Wait();
        }

        return proyectos;
    }
    set 
    { 
        prope = value; 
        RaisePropertyChanged(); 
    }
}

async private Task LoadData() 
{
    Prope = await clsStaticClassDataLoader.GetDataFromWebService();
}

这种方法有效,但是我不喜欢使用.Wait,因为如果服务不能快速响应,那会冻结屏幕.

This approach works, but I don't like the use of .Wait, because that can freeze the screen if the service doesn´t respond fast.

在这个问题上,您能指导我吗?

Can you please guide me on this matter?

预先感谢

推荐答案

我处理此问题的方法是在构造对象时开始加载属性的过程,但我没有等待结果.由于属性会在填充时通知,因此绑定可以正常工作.本质上它是这样的:

The way I handled this was to start the process of loading the property when the object was constructed, but I did not await the result. Since the property notifies when it is populated, the bindings worked just fine. Essentially it works like this:

public class MyClass : INotifyPropertyChanged
{
    private ObservableCollection<CProyecto> prope;

    public ObservableCollection<CProyecto> Prope
    {
        get { return prope; }
        set { prope = value; RaisePropertyChanged(nameof(Prope)); }
    }

    public MyClass()
    {
        // Don't wait or await.  When it's ready
        // the UI will get notified.
        LoadData();
    }

    async private Task LoadData() 
    {
        Prope = await clsStaticClassDataLoader.GetDataFromWebService();
    }
}

这非常有效,并且不会在UI中引起任何延迟或卡顿.如果您希望集合永远都不是null(IMO的一种良好做法),则可以使用空集合预先初始化prope字段.

This works very well, and does not cause any delays or stuttering in the UI. If you want the collection to never be null (a good practice IMO), you can pre-initialize the prope field with an empty collection.

这篇关于MVVM C#如何将异步数据加载到属性中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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