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


          在使用多线程的时候,开了多个线程一直在While(true),会造成CPU占用很高。这时候要在线程内加入一句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    }
  • 相关阅读:
    最简单跳转,待反混爻的合集
    搜索引擎劫持代码
    Warning: Cannot modify header information
    editplus 正则删换行
    在全程Linux環境部署IBM Lotus Domino/Notes 8.5
    3.5-杂项②
    3.4-杂项①
    3.3-ISDN
    3.2-帧中继②
    3.2-帧中继①
  • 原文地址:https://www.cnblogs.com/zhaoyihao/p/4533195.html
Copyright © 2020-2023  润新知