我有一個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進入大約一千次。
如果你想等待'proba'和richTextBoxLog初始化,然後讓它們合作..你需要[同步](http://msdn.microsoft.com/en-us/library/ms173179.aspx)在初始化結束時標記並顯示 – mtijn
問題是我在一個類中聲明瞭richTextBoxLog,並且線程在另一個類中啓動。 –