2013-07-04 44 views
0

我有以下代碼以異步方式更新進度欄,我注意到 它通過調用MessageBox的異步行爲。在這種情況下,它完美地工作 ,但是當我給睡眠1s(1000) MessageBox不會彈出,並且完整的進度條一次填充。 請告訴您爲什麼會發生這種情況。異步行爲

private void button1_Click(object sender, EventArgs e) 
    { 
     Update_Async async = new Update_Async(Update_Async_method); 
     progressBar1.BeginInvoke(async,10); 
     MessageBox.Show("Updation In Progress"); 


    } 

    public void Update_Async_method(int a) 
    { 
     this.progressBar1.Maximum = a; 
     for (int i = 1; i <= a; i++) 
     { 
      progressBar1.Value = a; 
      Thread.Sleep(10); 

    //Thread.Sleep(1000); 

     } 
    } 
+0

嘗試'progressBar1.value =我'不是一個。如果將其設置爲a,則將其設置爲完成。 – Codeguy007

+0

那麼,哪個位異步發生,即在另一個線程上?當您在控件上調用'BeginInvoke'時,將在主GUI線程上調用代碼。主GUI線程是'Click'事件處理程序已經運行的地方。因此,沒有異步性。 – Jodrell

+0

那麼,爲什麼我們有BeginInvoke On Controls.Please精心製作 – user1512186

回答

0

嘗試Update_Async.BeginInvoke(async, 10)代替,如果你想委託給asynchrnously運行,但你必須橫線上的更新進度條檢查。


在回答您的意見,非常類似於你在做什麼已經,

void UpdatingFunction(int value) 
{ 
    if (this.progressBar.InvokeRequired) 
    { 
     this.progressBar.BeginInvoke(UpdatingFunction, value); 
     return; 
    } 

    // Invoke not required, work on progressbar. 
} 

這也解釋了關於控制Invoke方法對。

+0

我該如何檢查?請詳述 – user1512186

+0

謝謝,現在清晰 – user1512186

0

Delegate.BeginInvoke將在一個線程中運行一次方法,然後處理它。如果你想在一個線程中重複做一些工作並返回中間結果,這是一個糟糕的選擇。如果這是你想要的,你應該使用BackgroundWorker。高度縮寫片段:

BackgroundWorker bw; 

YourFormConstructor() 
{ 
    ... 
    bw = new BackgroundWorker(); 
    bw.WorkerReportsProgress = true; 
    bw.DoWork += BackgroundCalculations; 
    bw.ProgressChanged += ShowBackgroundProgress; 
} 

private void button1_Click(object sender, EventArgs e) 
{ 
    bw.RunWorkerAsync(10); 
} 

void ShowBackgroundProgress(object sender, ProgressChangedEventArgs e) 
{ 
    this.progressBar.Value = e.ProgressPercentage; 
} 

static void BackgroundCalculations(object sender, DoWorkEventArgs e) 
{ 
    BackgroundWorker bw = sender as BackgroundWorker; 

    int max = (int)e.Argument; 
    for (int i = 0; i < max; i++) 
    { 
     bw.ReportProgress(i * 100/max); 
     Thread.Sleep(10); 
    } 

    bw.ReportProgress(100); 
    } 
}