作者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
1F:推 erspicu:厉害...那请问有修正解法吗? 05/31 19:34
2F:→ erspicu:会写WHILE是因为要一直重覆HTTP REQUEST 05/31 19:35
3F:→ erspicu:我C#好嫩 都不知道该怎麽办 苦手阿... 05/31 19:35
4F:→ iterator:先把comet_hook内的thread部分拿掉,因为你已经分出thread 05/31 19:42
5F:→ iterator:再来,你要做的可能是每隔一阵子透过http读取某个网页之类 05/31 19:43
6F:→ iterator:若不需很精准的时间间隔,直接在while内加上Thread.Sleep 05/31 19:45
7F:推 araonliu:其实WebClient或HttpRequest这些物件都有提供非同步的方 05/31 23:41
8F:→ araonliu:方, 另外提醒一点 , new一个新的thread就会占1MB的记忆体 05/31 23:42
9F:→ araonliu:所以用thread要小心 05/31 23:43