我在WinForms应用程序中使用MVP模式。我实现实时数据绘制图表(MSChart)的问题。 我有一些算法和演示者课程:
public class Algorithm
{
private double parameter1;
public void Execute()
{
for (int i = 0; i < 1000; i++)
{
...
if (i % 10 == 0)
{
parameter1 = parameter1 * 0.95;
}
...
}
}
public class MainWindowPresenter
{
public void RunAlgorithm()
{
Algorithm alg = new Algorithm();
alg.Execute();
}
}
我在Presenter类中执行此算法。我想通知View of change parameter1并将此更改传递给图表(MSChart),当然也可以在Chart中绘制。这是我的Form类:
public partial class MainWindow : Form, IMainWindowView
{
private MainWindowPresenter presenter;
...
private void btn_Start_Click(object sender, EventArgs e)
{
Task.Factory.StartNew(() => presenter.RunAlgorithm());
}
}
实时绘图没问题 - 我使用Task
,但如何通知视图和表单?
答案 0 :(得分:2)
我不完全清楚你要从你的示例代码中确切地想要实现什么,但根据所提供的信息,以下内容应该有效:
Algorithm
以展示其parameter1
值(例如,将其设为公共财产)。Algorithm
时都有一个RunAlgorithm
个实例,因此可能同时有多个parameter1
值,这似乎是无意的。使alg
成为MainWindowPresenter
类的成员,以便您有一个不再限定为RunAlgorithm
方法的实例。添加适当的locking以防止并发问题。Algorithm
和MainWindowPresenter
类,以通知观察者(表单/视图)对parameter1的更改。 MainWindowPresenter
可以转发Algorithm
类触发的事件。请注意,这些事件将在运行Task
的线程上运行。为了更新附加到这些事件的事件处理程序中的控件,您通常必须Invoke UI线程。