在使用多线程的时候,开了多个线程一直在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了
}
原标题:C# 多个线程一直跑着While(true)
关键词:C#