c# - 如何避免从构造函数调用长操作

标签 c# constructor

我使用 MVVM,我必须创建一个 ViewModel 类,它应该在打开 View 时加载大量数据。

基本上,当我创建 View 模型时,它应该使用数据库并获取数据。

我首先使用了这种方法:

public class MainViewModel
{
 public MainViewModel()
 {
   //set some properties
   Title = "Main view";
   //collect the data
   StartLongOperation();
 }

 private void StartLongOperation()
 {
   Thread t=new Thread(...);
   t.start();
 }
}

它在不阻塞 UI 线程的情况下工作并加载数据。

后来我找到this guideline关于如何使用构造函数,不建议从构造函数开始长时间运行。

√ DO minimal work in the constructor.

Constructors should not do much work other than capture the constructor parameters. The cost of any other processing should be delayed until required.

在我的例子中,打开 View 时需要数据。

我的第一个想法是使用事件

我应该如何避免从 construcTor 调用长操作?最佳做法是什么?

最佳答案

Miguel Castro 在他的一门出色的 Pluralsight 类(class)中谈到了解决这个问题的方法。他绑定(bind)到 View 模型中名为 ViewLoaded 的属性,当 View 加载时,该属性显然会被绑定(bind),这反过来会调用您的长时间运行的方法。

所以这进入 View (或所有 View 的基类以帮助重用):

    public ViewBase()
    {
        // Programmatically bind the view-model's ViewLoaded property to the view's ViewLoaded property.
        BindingOperations.SetBinding(this, ViewLoadedProperty, new Binding("ViewLoaded"));
    }

    public static readonly DependencyProperty ViewLoadedProperty =
        DependencyProperty.Register("ViewLoaded", typeof(object), typeof(UserControlViewBase),
        new PropertyMetadata(null));

这是 ViewModel 基类代码:

public object ViewLoaded
{
    get
    {
        OnViewLoaded();
        return null;
    }
}

protected virtual void OnViewLoaded() { }

只需覆盖 ViewModel 中的 OnViewLoaded() 方法并从那里调用长时间运行的方法。

关于c# - 如何避免从构造函数调用长操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29645152/

相关文章:

c# - 迭代时如何跳出 IAsyncEnumerable?

VS2005 中的 C# : will this() execute the base constructor code for an inherited class?

java - 根据子类型信息初始化父类(super class)型成员

inheritance - 从构造函数初始化 Typescript 类值

java:使用另一个类的构造函数

c# - 如何在 LINQ to Entities 中为 Entity Framework 对象使用谓词

c# - public T GetMyClass<T>() where T : MyClass, new() {/* 这是没有意义的吗? */}

c# - Winforms RadPageView 找控件

c# - 找到最少使用的排列

python - 对于自定义 Python 类,哪个 __repr__ 更好?