2014-12-03 41 views
0

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

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(); 
     } 

窗体上哪里是在窗体的Load我写下面的代码

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; 



    } 
+0

你打算如何让你的SP报告其进展,以便你可以捕获它?或者你是否会像它说的那样使其具有时间依赖性,至多总是需要2分钟? – romar 2014-12-03 05:58:01

+0

@romar我举一个例子,sp可能需要10分钟或半小时才能成功执行。 – 2014-12-03 06:01:22

+1

这意味着您剩下两个选项。 1.将进度条的ProgressBarStyle属性设置为“选取框”。这并没有显示真正的进展,但它只是通知用户该程序仍处于活动状态并正在处理任务(没有显示完成百分比)。 2.将您的存储过程分成几个阶段,并在每个阶段后将状态报告回您的winform。一种做法是这样的:http://stackoverflow.com/questions/6447152/progress-bar-for-stored-procedure – romar 2014-12-03 07:26:10

回答

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继续并执行this.ServiceProgressBar.Visible = false;语句。当然,在此期间让UI线程自由运行。

+0

什么是'等待Task.Run(()=>'在这里以及如何使用代码给我错误 – 2014-12-03 06:03:16

+0

你使用的是什么版本的Visual Studio?你需要VS2012或更高版本,或者你需要为.NET 4.0分别安装编译器和库。请参见http://msdn.microsoft.com/en-us /library/hh156528.aspx。如果你不能使用这个功能,还有其他的机制工作起来相似,只是不那么方便。如果你说你使用的是什么版本的C#/ .NET,那会有所帮助。 – 2014-12-03 07:12:28

+0

i我正在使用VS 2010 4.5版本 – 2014-12-03 07:30:43