Max*_* R. 5 c# linux serial-port raspberry-pi .net-core
当我尝试从 RaspberryPi 上的 Linux 中的串行端口 (uart) 读取数据时,在循环中我总是获得 5-10% 的 CPU 负载。由于串行端口应该是阻塞的,所以这不应该使用那么多的CPU负载,还是我错了?
我尝试了两个代码:
var port = new SerialPort("/dev/ttyUSB0", 57600);
port.Open();
while (true)
{
if (port.BytesToRead > 0)
{
while (port.BytesToRead > 0)
Console.Write($"{port.ReadByte().ToString("X2")} ");
Console.WriteLine("");
}
Thread.Sleep(100);
}
Run Code Online (Sandbox Code Playgroud)
static int blockLimit = 100;
static void Main(string[] args)
{
var port = new SerialPort("/dev/ttyUSB0", 57600);
port.Open();
byte[] buffer = new byte[blockLimit];
Action kickoffRead = null;
kickoffRead = delegate
{
port.BaseStream.BeginRead(buffer, 0, buffer.Length, delegate (IAsyncResult ar)
{
try
{
int actualLength = port.BaseStream.EndRead(ar);
byte[] received = new byte[actualLength];
Buffer.BlockCopy(buffer, 0, received, 0, actualLength);
raiseAppSerialDataEvent(received);
}
catch (IOException exc)
{
handleAppSerialError(exc);
}
kickoffRead();
}, null);
};
kickoffRead();
while (true)
Thread.Sleep(1000);
}
private static void handleAppSerialError(IOException exc)
{
throw new NotImplementedException();
}
private static void raiseAppSerialDataEvent(byte[] received)
{
Console.WriteLine(BitConverter.ToString(received));
}
Run Code Online (Sandbox Code Playgroud)
两者的结果相同:两个进程一起使用 5% 到 10% 的 cpu 负载

使用.NET Core 3.0 Preview 2andSystem.IO.Ports 4.6.0-preview-19073.11运行RaspberryPi 3b+withHypriotOS 1.10.0
就目前而言(NET Core 3.1)SerialPort 实现非常消耗 CPU 资源。我已根据此处的 dima117 响应将 Mono SerialPort 移植到 Net Standard 库 .NET Core - Use System.IO.Ports.SerialPort in Visual Studio Code
我已经发布到github了:
https://github.com/michaldobrodenka/System.IO.Ports.Mono
通过此串行端口实施,我的 allwinner h3 硬件上的 CPU 使用率从 25% 下降到 5%
| 归档时间: |
|
| 查看次数: |
3971 次 |
| 最近记录: |