星空网 > 软件开发 > ASP.net

C# 多个线程一直跑着While(true)

      在使用多线程的时候,开了多个线程一直在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#

C#
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流