我正在尝试通过微控制器从传感器读取多个串行端口。每个串口将接收超过 2000 个测量值(每个测量值是 7 个字节,全部为十六进制)。他们同时开火。现在我正在从 4 个串行端口轮询。此外,我将每个测量值转换为字符串并将其附加到 Stringbuilder。当我完成接收数据时,它们将被输出到一个文件中。问题是CPU消耗非常高,从80%到100%不等。
我浏览了一些文章并将 Thread.Sleep(100) 放在最后。当没有数据到来时,它会减少 CPU 时间。当 BytesToRead 小于 100 时,我还将 Thread.Sleep 放在每次轮询的末尾。它仅在一定程度上有所帮助。
有人可以建议一种解决方案来从串行端口轮询并处理我得到的数据吗?也许每次我得到一些东西时都附加会导致问题?
//I use separate threads for all sensors
private void SensorThread(SerialPort mySerialPort, int bytesPerMeasurement, TextBox textBox, StringBuilder data)
{
textBox.BeginInvoke(new MethodInvoker(delegate() { textBox.Text = ""; }));
int bytesRead;
int t;
Byte[] dataIn;
while (mySerialPort.IsOpen)
{
try
{
if (mySerialPort.BytesToRead != 0)
{
//trying to read a fix number of bytes
bytesRead = 0;
t = 0;
dataIn = new Byte[bytesPerMeasurement];
t = mySerialPort.Read(dataIn, 0, bytesPerMeasurement);
bytesRead += t;
while (bytesRead != bytesPerMeasurement)
{
t = mySerialPort.Read(dataIn, bytesRead, bytesPerMeasurement - bytesRead);
bytesRead += t;
}
//convert them into hex string
StringBuilder s = new StringBuilder();
foreach (Byte b in dataIn) { s.Append(b.ToString("X") + ","); }
var line = s.ToString();
var lineString = string.Format("{0} ---- {2}",
line,
mySerialPort.BytesToRead);
data.Append(lineString + "\r\n");//append a measurement to a huge Stringbuilder...Need a solution for this.
////use delegate to change UI thread...
textBox.BeginInvoke(new MethodInvoker(delegate() { textBox.Text = line; }));
if (mySerialPort.BytesToRead <= 100) { Thread.Sleep(100); }
}
else{Thread.Sleep(100);}
}
catch (Exception ex)
{
//MessageBox.Show(ex.ToString());
}
}
}