创建实时进度条winform

时间:2014-12-03 05:51:01

标签: c# .net winforms progress-bar

我正在创建一个Windows应用程序。在单击按钮时,我执行存储过程。存储过程的执行时间可以是1分钟或者可以是2分钟或更长时间。那么当我的SP执行时,如何显示当时的进度条。 以下是按钮点击的代码

 private void mnucollections_Click(object sender, EventArgs e)
    {
        if (_commonDAC == null)
             _commonDAC = new CommonDAC();
        if (MsgBox.Show("It is advised that you run Rebalance before entering Collection \n Run Rebalance now  ?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
        {
             frmProgressBar progress = new frmProgressBar(LoginName);
             progress.ShowDialog();    
        }
        else
        {
            frmCollections co = new frmCollections(LoginName);
            co.ShowDialog();
        }

在表单上我的进度条在表单上加载我在代码下面写

  private void frmProgressBar_Load(object sender, EventArgs e)
    {
       if (_commonDAC == null)
           _commonDAC = new CommonDAC();  

       this.ServiceProgressBar.Visible = true;
       int result = _commonDAC.RebalanceClient(); // Calling my store procedure 
       this.ServiceProgressBar.Visible = false;
        //progressBar1.Style = ProgressBarStyle.Blocks;



    }

1 个答案:

答案 0 :(得分:0)

调用存储过程将阻止frmProgressBar_Load()方法返回,这将阻止UI线程运行。你可以通过以下方式解决这个问题:

private async void frmProgressBar_Load(object sender, EventArgs e)
{
    if (_commonDAC == null)
        _commonDAC = new CommonDAC();  

    this.ServiceProgressBar.Visible = true;

    // Calling my store procedure 
    int result = await Task.Run(() => _commonDAC.RebalanceClient());

    this.ServiceProgressBar.Visible = false;
    //progressBar1.Style = ProgressBarStyle.Blocks;
}

这样,该方法将在运行RebalanceClient()方法的任务启动后返回,然后在任务完成后,它将继续将结果分配给result并执行{{ 1}}陈述。当然,让UI线程可以自由运行。