2011-11-02 63 views
0

我正在申請一個進度條和一個按鈕。如何在C sharp windows應用程序中處理交叉線程錯誤?

當按鈕點擊進度條價值將得到提高,這是源代碼,

private void Run() 
     {    
       progressBar1.Maximum = 1000; 
       progressBar1.Minimum = 0; 
       progressBar1.Step = 1; 

       for (int l_nIndex = 0; l_nIndex < 1000; l_nIndex++) 
       { 
         progressBar1.Value++; 
         Thread.Sleep(10); 
       } 
      } 


private void button1_Click(object sender, EventArgs e) 
     { 
       Run(); 
    } 

因此,當我運行應用程序,進度條價值是越來越增加了,但是當我嘗試移動窗戶沒有響應。

我不能以正常的線程方式運行它 - 它會拋出跨線程錯誤。

,所以我改變了這樣的代碼,

private void Run() 
     { 
       if (this.InvokeRequired) 
       { 
        this.Invoke(new MethodInvoker(this.Run)); 
       } 
       else 
       { 
        progressBar1.Maximum = 1000; 
        progressBar1.Minimum = 0; 
        progressBar1.Step = 1; 
        for (int l_nIndex = 0; l_nIndex < 1000; l_nIndex++) 
        { 
          progressBar1.Value++; 
          Thread.Sleep(10); 
        } 
       } 
     } 

private void button1_Click(object sender, EventArgs e) 
     { 
       Thread myThread = new Thread(new ThreadStart(Run)); 
       myThread.Start(); 
     } 

現在我可以能夠移動winodow,但是當我移動停止進度條,當我鬆開鼠標按鈕的斷點續傳。所以仍然在UI線程中執行。 如何更好地處理它。請幫助我做到這一點。

+0

見我的答案在這裏: 【答案爲 「跨線程操作失敗」] [1] [1]:http://stackoverflow.com/questions/1489374/cross-thread-operation-not-valid-does-not-kill-winforms-application-and-it-sh/1489452#1489452 – Spence

+1

這裏的一切都是錯誤的,我不能d關於它的任何事情。一切。爲什麼不只是使用Timer控件? –

回答

3

Invoke()通過從UI線程運行給定的委託來工作。因此,如果您使用Invoke()來運行您的整個方法,那麼您的整個方法從UI線程運行。

相反,你應該做你的實際工作其他線程,只是進行UI更新在UI線程中,僅通過Invoke()荷蘭國際集團執行更新的代碼的小位。

一個簡單的方法是使用標準庫中內置的BackgroundWorker類。

3

這已經回答了here - 在你的情況下,代碼應該是這個樣子:

this.BeginInvoke((Action)(() => progressBar1.Value++));