C#[Before 4.0] —如何在长度计算的回调之后更新GUI

问题描述

|| 我想知道实施以下方案的最佳实践。
public class MainWindow : Window
{

  public void MainWorkflow()
  {
    // initiate a work-thread to run LongCompute
    // when LongCompute finishes,update the corresponding GUI
    // for example,change the statusbar as \"Computation is done\"
  }

  private void LongCompute()
  {
    // a 2-minute computation and then update member variables 
    // after it finishes. I expect the main thread to use the 
    // updated member variables to update GUI later
  }
}
我正在寻找一个具体的好例子来说明此任务的最佳实践。 众所周知,不应使用工作线程来更新GUI,因为应该由创建它们的线程来更新GUI。另外,我知道以下两种模式: 情况I>主线程等待工作线程,然后在之后更新GUI。 例如, 在这种情况下,我们可以使用在AutoResetEvent中定义的WaitOne方法,该方法将由Set方法触发。但这不是一个好方法。 情况二>为工作线程设置一个回调函数,但是,该回调函数仍在工作线程中被调用,不利于处理GUI。     

解决方法

        正如@Jeff在评论中所说,为此使用BackgroundWorker。您指定要在后台线程上调用的函数,并指定在后台工作完成后要调用的另一个函数。     

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...