作者iterator (rotareti)
看板C_Sharp
標題Re: [問題] thread再問
時間Tue May 31 18:35:51 2011
※ 引述《erspicu (.)》之銘言:
: private void button1_Click(object sender, RoutedEventArgs e)
: {
: Thread t1 = new Thread(comet_hook);
: t1.Start();
: }
: public void comet_hook()
: {
: while (true)
: {
: System.Threading.Thread thread =
: new System.Threading.Thread(
: new System.Threading.ThreadStart(
: delegate()
: {
: richTextBox1.Dispatcher.Invoke(
: System.Windows.Threading.DispatcherPriority.Normal,
: new Action(
: delegate()
: {
: richTextBox1.AppendText("aaa");
: }
: )
: );
: }
: ));
: thread.Start();
: }
: }
這個程式有兩個地方會卡住:
第一個是 comet_hook 本體,
首先我們先不管 thread 啟動後執行的部分. (啟動後就屬於另外一個 thread)
簡化後這個 comet_hook 會變成這樣:
while (true)
{
new System.Threading.Thread()
thread.Start();
}
這裡就變成一個 busy loop, 程式會不斷的 create/start new thread,
執行後可以開啟 task manager 看, process 的 thread 數量將會快速的飆漲,
直到耗盡系統資源.
(除非有需要同時執行 n 個 task, 不然不需要寫成這個樣子)
第二個是 RichTextBox.AppendText,
這個 method 內部會 lock 或是 wait 某些元件. 使用 TextBox 則無此現象.
另外, 若不斷的要求 UI thread 處理你插入的工作,
UI thread 將會來不及處理自己原來的工作,
視窗 UI 會沒有反應, 拖動/按鈕等等也會無法運作.
(這時候可以視狀況, 加入 Thread.Sleep, 別一直送出要求,
讓 UI thread 能有時間處理自己的工作.)
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.113.23.102
推 erspicu:厲害...那請問有修正解法嗎? 05/31 19:34
→ erspicu:會寫WHILE是因為要一直重覆HTTP REQUEST 05/31 19:35
→ erspicu:我C#好嫩 都不知道該怎麼辦 苦手阿... 05/31 19:35
→ iterator:先把comet_hook內的thread部分拿掉,因為你已經分出thread 05/31 19:42
→ iterator:再來,你要做的可能是每隔一陣子透過http讀取某個網頁之類 05/31 19:43
→ iterator:若不需很精準的時間間隔,直接在while內加上Thread.Sleep 05/31 19:45
推 araonliu:其實WebClient或HttpRequest這些物件都有提供非同步的方 05/31 23:41
→ araonliu:方, 另外提醒一點 , new一個新的thread就會佔1MB的記憶體 05/31 23:42
→ araonliu:所以用thread要小心 05/31 23:43