2013-05-29 79 views
1

我想知道在線程中運行時是否有方法來動態更改傳遞給方法的參數。在線程中執行過程中更改參數值

例如:

trdColCycl thread = new Thread (() => this.ColorsCycling (true)); 
trdColCycl.Start(); 

trdColCycl thread = new Thread (new ParameterizedThreadStart (this.ColorsCycling)); 
trdColCycl.Start(true); 

,然後我想作爲參數傳遞到運行值false不知所云,這可能嗎? (在這個例子中,我想動態地改變參數值以退出線程內的循環而不使用全局變量)

感謝您的幫助。

回答

2

您可以創建意味着兩個線程

之間通信的共享變量
class ArgumentObject 
{ 
    public bool isOk; 
} 

// later 
thread1Argument = new ArgumentObject() { isOk = true }; 
TrdColCycl thread = new Thread (() => this.ColorsCycling (thread1Argument)); 
trdColCycl.Start(); 

// much later 
thread1Argument.isOk = false; 

編輯:

或者,您可以通過布爾作爲參考,而不是:

bool isOk = true; 
TrdColCycl thread = new Thread (() => this.ColorsCycling (ref isOk)); 
trdColCycl.Start(); 

// later 
isOk = false; 

在這兩種情況下, ,您必須修改您方法的簽名:

// original 
void ColorsCycling(bool isOk) 
// should be 
void ColorsCycling(ArgumentObject argument) // for option 1 
// or 
void ColorsCycling(ref bool isOk) // for option 2 
+0

非常感謝您的所有這些偉大的選擇! –