本文介绍了如何从业务/模型类发送进度更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个具有分层架构的应用程序.在视图上,我们使用 MVC 或 MVVM.模型被视为领域,它包含业务逻辑的一个很好的部分.

Let's say we have an application that has a layered architecture. On the view we use a MVC or MVVM. The model is treated as the domain, it has a good part of the business logic.

现在假设我们在模型中有一个需要一些时间的方法.例如,必须对对象的每个项目进行复杂的计算或处理.

Now let's say we have, in the model, a method that takes some time. A complicated calculation or a treatment that has to be done to each items of an object for example.

在 UI 中,我们希望显示一个进度条和一个文本,以显示计算的当前步骤(例如一个包含所有过程历史的列表框).

In the UI, we would like to display a progress bar and a text that would display the current step of the calculation (for example a listbox with all the process history).

你会怎么做?如何从模型中发送进程的进度信息,以及如何连接Controller或ViewModel使其更新进度?

How would you do that? How to send from the model the information of the progress of the process and how to hook up the Controller or ViewModel so that it will update the progress?

推荐答案

我经常通过以下方式实现这一点.我的业务层流程需要很长时间才能运行,它每隔一段时间就会引发事件以表明它正在达到特定的里程碑".您决定通过事件发出哪些里程碑以及其中多少个里程碑.如果你的耗时过程是一个简单的循环,你可以选择,例如,循环中每 10% 的项目一次又一次地引发相同的事件.如果它是一个具有不同阶段的流程,您可以选择在每个阶段完成时引发不同的事件.

I often implement this in the following manner. My business-layer process, which takes a long time to run, raises events every so often to indicate that it's hitting specific "milestones". You decide what milestones to signal through events and how many of them. If your time-consuming process is a plain loop, you may choose, for example, to raise the same event again and again every 10% of the items in the loop. If it is a process with distinct phases, you may choose to raise a different event as each phase is completed.

现在,您的表示层订阅这些事件并相应地采取行动,更新进度条、文本或其他内容.

Now, your presentation layer subscribes to those events and acts in consequence, updating the progress bar, the text or whatever.

这种机制很好,因为:

  1. 业务层保持独立于表示层中可能发生的事情.
  2. 很容易扩展双向通信.您可以轻松更改事件,以便表示层(或任何其他订阅者)可以返回取消标志,以便业务层知道必须取消长时间运行的流程.
  3. 它允许同步或异步工作.也就是说,您可以将它用于阻塞调用(即您的表示层和业务层共享同一线程)或非阻塞调用(即您的业务层使用后台工作线程).System.ComponentModel.BackgroundWorker 类可用于后一种情况,但如果您想引发多种类型的事件,那就不太好.
  1. The business layer stays independent of what may go on up in the presentation layer.
  2. It is easy to extend for bi-directional communication. You can easily alter events so that the presentation layer (or any other subscriber) can return a cancel flag so that the business layer knows that a long-running process must be cancelled.
  3. It admits either synchronous or asynchronous work. That is, you can use it on blocking calls (i.e. your presentation and business layer share the same thread) or non-blocking calls (i.e. your business layer uses a background worker thread). The System.ComponentModel.BackgroundWorker class can be used in the latter case, but it's not too good if you want to raise multiple types of events.

希望这会有所帮助.

这篇关于如何从业务/模型类发送进度更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 00:22