BackGroundWorker悬挂水晶报表

时间:2013-11-13 12:20:34

标签: c# winforms crystal-reports backgroundworker

我有一个Crystal Report,它使用TreeView从Form上的按钮生成各种DataTable。我想运行BackGroundWorker,因此我可以添加ProgressBar,因为生成的Crystal Report需要一些时间。我已经读到,首先我需要将BackGroundWorker添加到控件中,并将所有生成que长时间运行进程的逻辑代码放在BackGroundWorker的DoWork事件上。我是这样做的:

//bgwBackThread is the name of the BackGroundWorkerObject
private void bgwBackThread_DoWork(object sender, DoWorkEventArgs e)
    {
        DataTable reporte = preReportDouble(Ot, Oth);
        DataTable hh = reporteHH(Ot, Oth);
        DataTable otNoCosto = otNoCost(Ot, Oth);
        DataTable dethh = detalleHH(Ot, Oth);

        //cryrepo is a Form which holds a CrystalReportViewer
        InformeMaquina cryrepo = new InformeMaquina();
        cryrepo.Informe = reporte;
        cryrepo.Hh = hh;
        cryrepo.SinCosto = otNoCosto;
        cryrepo.DetHh = dethh;
        cryrepo.Show();
    }

之后我将方法RunWorkerAsync()分配给生成Form的按钮 前

   private void btnReporte_Click(object sender, EventArgs e)
    {
        bgwBackThread.RunWorkerAsync();
        //Below its commented because before of trying BackGroundWorker I just used the code here.
        /*DataTable reporte = preReportDouble(Ot, Oth);
        DataTable hh = reporteHH(Ot, Oth);
        DataTable otNoCosto = otNoCost(Ot, Oth);
        DataTable dethh = detalleHH(Ot, Oth);

        InformeMaquina cryrepo = new InformeMaquina();
        cryrepo.Informe = reporte;
        cryrepo.Hh = hh;
        cryrepo.SinCosto = otNoCosto;
        cryrepo.DetHh = dethh;
        cryrepo.Show();
        */
    }

问题是当我按下上面的代码按下报告按钮时。它加载了保存Que Crystal Report的Form,但是这个Forms挂起(即使在Debug中)。没有使用BackGroundWorker它工作正常,但有延迟。我读过它可能是因为我从非UI线程加载Form,并且我必须从UI取消绑定然后重新绑定。这是问题吗?如果是,我怎么解开然后重新绑定??

你的帮助非常渺茫。

1 个答案:

答案 0 :(得分:1)

尝试在表单中创建一个私有类来保存DataTable信息(我假设这是一个耗时的部分);

private class ReportTables {
  public DataTable reporte;
  public DataTable hh;
  public DataTable otNoCosto;
  public DataTable dethh;
}

创建DataTables并更新e.Result属性中的结果:

private void bgwBackThread_DoWork(object sender, DoWorkEventArgs e)
{
  ReportTables rt = new ReportTables();
  rt.reporte = preReportDouble(Ot, Oth);
  rt.hh = reporteHH(Ot, Oth);
  rt.otNoCosto = otNoCost(Ot, Oth);
  rt.dethh = detalleHH(Ot, Oth);
  e.Result = rt;
}

然后在Completed事件中,显示表单:

void bgwBackThread_RunWorkerCompleted(object sender, 
                                      RunWorkerCompletedEventArgs e) {
  if (e.Error != null) {
    MessageBox.Show(e.Error.Message);
  } else {
    ReportsTables rt = e.Result as ReportTables;

    //cryrepo is a Form which holds a CrystalReportViewer
    InformeMaquina cryrepo = new InformeMaquina();
    cryrepo.Informe = rt.reporte;
    cryrepo.Hh = rt.hh;
    cryrepo.SinCosto = rt.otNoCosto;
    cryrepo.DetHh = rt.dethh;
    cryrepo.Show();
  }
}