C# 多个线程一直跑着While(true)
生活随笔
收集整理的這篇文章主要介紹了
C# 多个线程一直跑着While(true)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
? ? ? 在使用多線程的時候,開了多個線程一直在While(true),會造成CPU占用很高。這時候要在線程內(nèi)加入一句Thread.Sleep(1),讓他稍微睡一下。就不會消耗那么多CPU了。
? ? ? ?代碼:
1 Thread dataThread = new Thread(delegate() 2 { 3 while (threadFlag) 4 { 5 if (Port != null && Port.IsOpen) 6 { 7 length = Port.BytesToRead; 8 if (length > 0) 9 { 10 11 bytes = new byte[length]; 12 Port.Read(bytes, 0, length); 13 14 tcp.SendData(bytes); 15 16 if (textBox.InvokeRequired) 17 { 18 19 textBox.Invoke(new Action<string>(s => 20 { 21 textBox.AppendText(s + Environment.NewLine); 22 textBox.SelectionStart = textBox.TextLength; 23 textBox.ScrollToCaret(); 24 25 }), System.Text.Encoding.ASCII.GetString(bytes)); 26 27 } 28 else 29 { 30 textBox.AppendText(System.Text.Encoding.ASCII.GetString(bytes) + Environment.NewLine); 31 textBox.SelectionStart = textBox.TextLength; 32 textBox.ScrollToCaret(); 33 34 } 35 } 36 37 } 38 Thread.Sleep(1); 39 } 40 41 }); 42 dataThread.IsBackground = true; 43 dataThread.Name = PortName; 44 dataThread.Start(); 45 } 46 47 }?
轉(zhuǎn)載于:https://www.cnblogs.com/zhaoyihao/p/4533195.html
總結(jié)
以上是生活随笔為你收集整理的C# 多个线程一直跑着While(true)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 自动增益(AGC)算法FPGA实现
- 下一篇: 兼容性记录-class属性