在使用多線程的時候,開了多個線程一直在While(true),會造成CPU占用很高。這時候要在線程內加入一句Thread.Sleep(1),讓他稍微睡一下。就不會消耗那麼多CPU了。
代碼:
Thread receThread=new Thread(
delegate()
{
while (socketFlag)
{
if(SocketClient==null||!SocketClient.Connected ||SocketClient.Available<=0)
{
continue;
}
length = SocketClient.Receive(bytes, 0, bytes.Length, SocketFlags.None);
if (length > 0)
{
serialPortCls.SendData(bytes, length);
if (textBox.InvokeRequired)
{
textBox.Invoke(new Action<string>(s =>
{
textBox.AppendText(s + Environment.NewLine);
textBox.SelectionStart = textBox.TextLength;
textBox.ScrollToCaret();
}), Encoding.ASCII.GetString(bytes));
}
else
{
textBox.AppendText(System.Text.Encoding.ASCII.GetString(bytes) + Environment.NewLine);
textBox.SelectionStart = textBox.TextLength;
textBox.ScrollToCaret();
}
}
Thread.Sleep(1); //睡1ms再繼續干活,就不會消耗那麼多CPU了
}