谁应该处理MVC中的线程? [英] Who should handle threading in MVC?

查看:63
本文介绍了谁应该处理MVC中的线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

长时间运行的任务通常在后台线程中执行,以防止UI冻结.线程逻辑似乎可以驻留在视图或控制器中.

Long-running tasks are usually executed in a background thread to keep the UI from freezing. It seems the threading logic could reside in either the view or in the controller.

作为一个示例(在C#中),假设有一个名为RunAsync的方法在后台线程中运行委托,这有两种方法:

As an example (in C#), suppose there is a method named RunAsync that runs a delegate in a background thread, here are two ways of doing it:

// Option 1

public class View {
  public void OnButtonClicked() {
    RunAsync(() => controller.DoSomething());
  }
}

public class Controller {
  public void DoSomething() {
    model.Foo();
  }
}

或:

// Option 2

public class View {
  public void OnButtonClicked() {
    controller.DoSomething();
  }
}

public class Controller {
  public void DoSomething() {
    RunAsync(() => model.Foo());
  }
}

以一种或另一种方式进行操作是否有优势?

Is there an advantage to doing it one way or the other?

推荐答案

我看到控制器的两个参数负责线程安全.

I see two arguments for the Controller having the responsibility for Thread safety.

  1. 许多视图(至少在概念上)可以重用该控制器.我们避免重复自己,而是将RunAsync()放在Controller中而不是在许多视图中.
  2. 只有Controller真正知道"是否需要任何此类线程.实际上,我们将来可能会更改控制器.因此,我们有一种单一责任"的思维方式.控制器既决定是否需要RunAsynch(),又要确保已完成.

这篇关于谁应该处理MVC中的线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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