gpt4 book ai didi

c# - .NET core 3.0 System.IO.Ports SerialPort始终在RPI上使用5-10%的CPU

转载 作者:行者123 更新时间:2023-12-02 04:40:47 27 4
gpt4 key购买 nike

当我尝试在RaspberryPi上的Linux中从串行端口(uart)读取时,在循环中时,我总是会得到5-10%的CPU负载。由于SerialPorts应该被阻塞,因此不应使用那么多的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);
}


进阶密码

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));
}


两者具有相同的结果:两个进程同时使用5%到10%的CPU负载
htop cpu%

在运行 .NET Core 3.0 Preview 2System.IO.Ports 4.6.0-preview-19073.11上使用 RaspberryPi 3b+HypriotOS 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

通过此SerialPort实施,我的全能型硬件H3的CPU使用率从25%下降至5%

关于c# - .NET core 3.0 System.IO.Ports SerialPort始终在RPI上使用5-10%的CPU,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54903630/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com