在 Winforms (C#) 中使用 MVP 模式的后台工作程序

2024-03-11

我一直在尝试使用 MVP 模式重构应用程序的意大利面条代码。但现在我正在为此苦苦挣扎:

具有调用 DoWork 方法(后台工作者)的按钮的表单,这是一个很长的操作。我的问题是,如果我将长操作从视图移到演示器中,那么如何将此操作的进度更改发送到视图? BGW也必须在Presenter中吗? 您能给我一个如何执行此操作的示例吗?

先感谢您。


这概述了BackgroundWorker的使用:

private BackgroundWorker _backgroundWorker;

public void Setup( )
{
    _backgroundWorker = new BackgroundWorker();
    _backgroundWorker.WorkerReportsProgress = true;
    _backgroundWorker.DoWork +=
      new DoWorkEventHandler(BackgroundWorker_DoWork);
    _backgroundWorker.ProgressChanged +=
      new ProgressChangedEventHandler(BackgroundWorker_ProgressChanged);
    _backgroundWorker.RunWorkerCompleted +=
      new RunWorkerCompletedEventHandler(BackgroundWorker_RunWorkerCompleted);

    // Start the BackgroundWorker
    _backgroundWorker.RunWorkerAsync();
}

void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    // This method runs in a background thread. Do not access the UI here!
    while (work not done) {
        // Do your background work here!

        // Send messages to the UI:
        _backgroundWorker.ReportProgress(percentage_done, user_state);
        // You don't need to calculate the percentage number if you don't
        // need it in BackgroundWorker_ProgressChanged.
    }
    // You can set e.Result = to some result;
}

void BackgroundWorker_ProgressChanged(object sender,
                                      ProgressChangedEventArgs e)
{
    // This method runs in the UI thread and receives messages from the backgroud thread.

    // Report progress using the value e.ProgressPercentage and e.UserState
}

void BackgroundWorker_RunWorkerCompleted(object sender,
                                         RunWorkerCompletedEventArgs e)
{
    // This method runs in the UI thread.
    // Work is finished! You can display the work done by using e.Result
}

UPDATE

此BackgroundWorker 必须位于原因的演示者中。 MVP、MVC 或 MVVM 等模式的想法是从视图中删除尽可能多的代码。视图将仅具有特定于视图本身的代码,例如在视图中创建视图或绘图。Paint事件处理程序等等。视图中的另一种代码是与演示者或控制器通信所需的代码。然而,呈现逻辑必须在呈现器中。

你会使用BackgroundWorker_ProgressChanged在 UI 线程中运行以将更改发送到视图的方法。通过调用视图的公共方法或通过设置视图的公共属性或通过将视图的属性或其控件的属性绑定到视图来公开视图可以附加的公共属性。 (这是从 MVVM 模式借用的。)演示者必须实现INotifyPropertyChanged如果您决定将视图绑定到演示者的属性,以便通知视图属性已更改。

Note:除 UI 线程之外的其他线程不允许直接与视图交互(如果尝试这样做,则会抛出异常)。因此,BackgroundWorker_DoWork 无法直接与视图交互,因此会调用 ReportProgress,而 ReportProgress 又会在 UI 线程中运行 BackgroundWorker_ProgressChanged。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Winforms (C#) 中使用 MVP 模式的后台工作程序 的相关文章

随机推荐