如何在显示 ProgressBar 时执行方法,然后显示 Form?

How do I execute a method while displaying a ProgressBar, then show a Form after?

如何在显示 ProgressBar 时执行方法,然后显示 Form?

private void btnCienciaEmissao_Click(object sender, EventArgs e)
{
    var progressForm = new ProgressBar.frmPBText();
    var retornoManifestacao = new frmConsultaNotaEmitidaContraCNPJAntigoRetornoManifestacao();

    var threadProcesso = new Thread(() =>
        {
            Parametros.DgvRetornoManifestacao = ExecutaManifestacao();
            progressForm.BeginInvoke(new Action(() => { progressForm.Close(); }));
            retornoManifestacao.BeginInvoke(new Action(() => { retornoManifestacao.dgvRetornoManifestacaoDataSource(Parametros.DgvRetornoManifestacao);}));
        });

    threadProcesso.Start();

    progressForm.Show();

    // I WANT TO SHOW RetornoManifestacao ONLY AFTER threadProcesso FINISHED
    retornoManifestacao.Show();
}

我希望表格 retornoManifestacaothreadProcesso 完成后显示

如果我使用 retornoManifestacao.Show(),像上面一样,表单将出现在 threadProcesso 结束之前。我需要它只在线程结束后出现。

我尝试使用 threadProcesso.Join(),但 progressForm 卡住了。

我的progressForm有跑马灯样式ProgressBar,所以没必要报告进度。

您只需将对 Show() 的调用移动到您的线程中,以便它作为线程执行的最后一件事来执行。例如:

private void btnCienciaEmissao_Click(object sender, EventArgs e)
{
    var progressForm = new ProgressBar.frmPBText();
    var retornoManifestacao = new frmConsultaNotaEmitidaContraCNPJAntigoRetornoManifestacao();

    var threadProcesso = new Thread(() =>
        {
            Parametros.DgvRetornoManifestacao = ExecutaManifestacao();
            progressForm.BeginInvoke((MethodInvoker)(() =>
            {
                // These can (and should) all go in a single invoked method
                progressForm.Close();
                retornoManifestacao.dgvRetornoManifestacaoDataSource(Parametros.DgvRetornoManifestacao);
                retornoManifestacao.Show();
            }));
        });

    threadProcesso.Start();

    progressForm.Show();
}

也就是说,如果您使用的是 .NET 4.5,在我看来,总体上稍微不同的方法会更好:

private async void btnCienciaEmissao_Click(object sender, EventArgs e)
{
    var progressForm = new ProgressBar.frmPBText();

    progressForm.Show();
    Parametros.DgvRetornoManifestacao = await Task.Run(() => ExecutaManifestacao());
    progressForm.Close();

    var retornoManifestacao = new frmConsultaNotaEmitidaContraCNPJAntigoRetornoManifestacao();

    retornoManifestacao.dgvRetornoManifestacaoDataSource(Parametros.DgvRetornoManifestacao);
    retornoManifestacao.Show();
}