C # multiple threads keep running While (true ),
When multithreading is used, multiple threads are always running While (true), which causes high CPU usage. In this case, add Thread. Sleep (1) to the Thread and let him Sleep a little. It won't consume that much CPU.
Code:
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); // continue to work after 1 ms, so it will not consume so much CPU.
}