优化代码:public static string ReadRegister(SerialPort sp, string registerAddr, int numberOfPoints, string type) { try { sp.DiscardOutBuffer(); sp.DiscardInBuffer(); string value = null; byte[] readbytes = Read(registerAddr, numberOfPoints); sp.Write(readbytes, 0, readbytes.Length); Byte[] ReceivedData = new Byte[4 + numberOfPoints * 2]; //创建接收字节数组 int i = 0; //long timespan2 = 0; //System.Diagnostics.Stopwatch watch2 = new System.Diagnostics.Stopwatch(); //watch2.Start(); //开始监视代码运行时间 while (true) { i++; if (sp.BytesToRead == 4 + numberOfPoints * 2) { sp.Read(ReceivedData, 0, sp.BytesToRead); //读取所接收到的数据 byte[] temp = new byte[numberOfPoints]; for (int j = 0; j < numberOfPoints; j++) { try { temp[j] = Convert.ToByte(Convert.ToInt16((Chr(ReceivedData[j * 2 + 1]) + Chr(ReceivedData[j * 2 + 2])), 16)); } catch { return null; } } switch (type) { case "float": value = BytesToFloat(temp).ToString("f4"); break; case "int32": value = BytesToInt32(temp).ToString(); break; case "int16": //value = Status(BytesToInt16(temp)); value = BytesToInt16(temp).ToString(); break; case "byte": value = Convert.ToString(temp[0], 2).PadLeft(8, '0'); break; case "2bytes": value = Convert.ToString(temp[0], 2).PadLeft(8, '0'); break; case "bit": value = Convert.ToString(temp[0], 2).Substring(0, 1); break; } break; } if (i > 100000) break;//10000=440ms左右 } //watch2.Stop(); //停止监视 //timespan2 = watch2.ElapsedMilliseconds; //获取当前实例测量得出的总时间 //return ReceivedData; return value; } catch { return null; } }
时间: 2023-06-24 21:06:12 浏览: 110
PPI-SerialPort.zip_ppi_s7200_serialport_site:www.pudn.com
public static string ReadRegister(SerialPort sp, string registerAddr, int numberOfPoints, string type)
{
try
{
sp.DiscardOutBuffer();
sp.DiscardInBuffer();
string value = null;
byte[] readbytes = Read(registerAddr, numberOfPoints);
sp.Write(readbytes, 0, readbytes.Length);
Byte[] ReceivedData = new Byte[4 + numberOfPoints * 2];
int i = 0;
while (i <= 100000)
{
i++;
if (sp.BytesToRead == 4 + numberOfPoints * 2)
{
sp.Read(ReceivedData, 0, sp.BytesToRead);
byte[] temp = new byte[numberOfPoints];
for (int j = 0; j < numberOfPoints; j++)
{
if (ReceivedData.Length >= j * 2 + 2)
{
temp[j] = Convert.ToByte(Convert.ToInt16((Chr(ReceivedData[j * 2 + 1]) + Chr(ReceivedData[j * 2 + 2])), 16));
}
}
switch (type)
{
case "float":
value = BytesToFloat(temp).ToString("f4");
break;
case "int32":
value = BytesToInt32(temp).ToString();
break;
case "int16":
value = BytesToInt16(temp).ToString();
break;
case "byte":
value = Convert.ToString(temp[0], 2).PadLeft(8, '0');
break;
case "2bytes":
value = Convert.ToString(temp[0], 2).PadLeft(8, '0');
break;
case "bit":
value = Convert.ToString(temp[0], 2).Substring(0, 1);
break;
}
break;
}
Thread.Sleep(1);
}
return value;
}
catch
{
return null;
}
}
优化点:
- 添加了对 ReceivedData 数组长度的判断,避免数组越界;
- 将循环次数限制改为 100000,避免死循环;
- 在循环中添加了 Thread.Sleep(1) 来减小 CPU 占用率;
- 去掉了不必要的注释。
阅读全文