2011-09-27 56 views
1

我有一個richTextBoxLog這是公共和靜態。兩條線程通訊

我宣佈它後,我開始一個新的線程,它初始化名爲proba的新變量。 richTextBoxLog應該從proba得到值。我想richTextBoxLog初始化,而proba正在初始化。

我想寫類似:

richTextBoxLogFile.richTextBoxLog.Text += proba; 

但是,當我把它寫在由前面提到的線程調用的方法,我得到一個異常:"Cross-thread operation not valid: Control 'richTextBoxLog' accessed from a thread other than the thread it was created on."

我能寫的東西像這樣:停止線程,然後初始化richTextBoxLog,然後再次啓動線程,然後停止它,並且在初始化richTextBoxLog結束時繼續相同。

編輯:我嘗試使用此:

context.Post(新SendOrPostCallback(newMethod),(對象)PROBA);

其中context是主線程的上下文,newMethod初始化richTextBoxLog的值。然而,這一呼籲是在由新線程啓動方法,在一個while循環:

while (-1 != (ch = _reader.Read())) 
     { 
      Console.Write((char)ch); 
      proba += ((char)ch).ToString(); 
      context.Post(new SendOrPostCallback(newMethod), (object)proba);     
     } 
     _complete.Set(); 
    } 

我現在的問題是,我想,當我在while循環進入newMethod被稱爲每次。但是,發生的事情是:while循環結束,並且在此之後newMethod進入大約一千次。

+0

如果你想等待'proba'和richTextBoxLog初始化,然後讓它們合作..你需要[同步](http://msdn.microsoft.com/en-us/library/ms173179.aspx)在初始化結束時標記並顯示 – mtijn

+0

問題是我在一個類中聲明瞭richTextBoxLog,並且線程在另一個類中啓動。 –

回答

1

您需要PROBA要調用的方法:

System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke(
    new Action(() => 
     { 
       //do stuff with proba 
     } 
    )); 

//編輯:

等待,這是一個比較複雜的。調度程序是一個可以簡單地從其他線程執行方法的對象。這意味着您需要在帶有proba的線程中創建一個調度程序,並在其他線程中使用該調度程序來執行上述方法。