gpt4 book ai didi

c# - 使用 Async await 方法从串口异步读取

转载 作者:太空狗 更新时间:2023-10-30 00:10:51 25 4
gpt4 key购买 nike

我正在使用这种方式从串口读取:

public static void Main()
{
SerialPort mySerialPort = new SerialPort("COM1");

mySerialPort.BaudRate = 9600;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;

mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

mySerialPort.Open();

Console.WriteLine("Press any key to continue...");
Console.WriteLine();
Console.ReadKey();
mySerialPort.Close();
}
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
Debug.Print("Data Received:");
Debug.Print(indata);
}

据我们所知,这种 API 称为基于事件的异步模式 (EAP),我想使用 Async Await 方法编写上面的代码。

PS:使用上面的代码有时我会得到错误的数据
提前致谢

最佳答案

您还可以从 SerialPort.BaseStream 读取数据。它属于 Stream 类型,因此支持可等待的 ReadAsync() 方法。将其转换为字符串取决于您,使用正确的编码。 SerialPort 的默认值是 ASCIIEncoding。

关于c# - 使用 Async await 方法从串口异步读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18815380/

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