2013-05-02 36 views
0

我有一個自定義窗體,在主類(主線程)中產生一個自定義進度條。然後我產生一個線程併發送一個ThreadStart函數。此線程啓動功能應該更新在自定義控制進度條,但犯規:線程沒有更新進度條控件 - C#

class MyClass 
{ 
...... 
//Custom form with progress bar 
public CustomFormWithProgressBar statusScreen = new CustomFormWithProgressBar(0); 
//thread to use 
private Thread myThread; 

..... 
//Linked to a button to trigger the update procedure. 
void ButtonPressEvent(.......) 
{ 
    //create a sub thread to run the work and handle the UI updates to the progress bar 
    myThread = new Thread(new ThreadStart(ThreadFunction)); 
    myThread.Start(); 
} 
..... 
//The function that gets called when the thread runs 
public void ThreadFunction() 
{ 
    //MyThreadClass myThreadClassObject = new MyThreadClass(this); 
    //myThreadClassObject.Run(); 
    statusScreen.ShowStatusScreen(); 

    for (int i = 0; i < 100; i++) 
    { 
     statusScreen .SetProgressPercentage(i); 
     Thread.Sleep(20); 
    } 
    statusScreen.CloseStatusScreen(); 
} 

現在我statusScreen形式只是坐在和什麼也不做。沒有更新發生。但我已經確認子線程確實已創建,而我在ThreadFunction中,我在新線程上運行。通過Visual Studio中的Thread窗口確定這一點。

爲什麼我的狀態屏幕進度百分比更新沒有顯示?我如何獲得更新以將新值推入進度屏幕並讓它顯示實時?

請注意,發送到狀態屏幕功能的整數值表示完成百分比。 Thread.Sleep只是查看更新是否/何時發生。

請注意,這不是一個重繪問題。當進度百分比傳遞到自定義進度條時,我稱爲「無效」

回答

2

您無法更新從另一個線程控制。

正確的方法 - 爲您的目的使用BackgroundWorker。 另一種方式(幾乎正確的方式) - 使用Control.Invoke方法。 還有另一個幾乎正確的方法 - 使用SynchronizationContext。

但是,您可以選擇權力的黑暗面並使用CheckForIllegalCrossThreadCalls - Control類的靜態屬性並將其設置爲false。

+0

我試着調用和backgroundWorker,我無法得到它。你是否給出了一個應用於我的OP代碼的例子?我會非常感激 – 2013-05-02 20:42:54

+1

當然。 1.在非GUI線程中創建進度窗口。移動statusScreen.ShowStatusScreen();到ButtoPressEvent。然後在ButtonPressEvent中創建BackgroundWorker。爲DoWork和Completed,ProgressChanged事件創建處理程序。請參閱MSDN上的BackgroundWorker幫助。並在Completed事件中關閉statusScreen。 – Uzzy 2013-05-02 20:53:08

+0

解決了它。謝謝 – 2013-05-02 21:14:28

1

由於您的進度條位於UI /主線程上,因此您的線程無法修改它,而不會導致交叉線程引用異常。您應該將操作調用到主線程。

例子:

// in your thread 
this.Invoke((MethodInvoker)delegate { 
    statusScreen.SetProgressPercentage(value); // runs on main thread 
}); 
+0

我剛剛在我的copmuter上試了一遍,它崩潰了。所以我會再試一次,並讓你知道 – 2013-05-02 20:44:15

+0

你是什麼意思,拋出異常? – Ryan 2013-05-02 20:44:49

+0

沒有,它只是鎖定了系統,黑色屏蔽了。難以重新啓動哈哈 – 2013-05-02 20:46:25