2014-12-03 67 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