我正在使用这种方式从串口读取:
I'm using this way for reading from serial port :
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方法编写上面的代码.
as we know This kind of API is called the Event-based Asynchronous Pattern (EAP), I want to write above code using Async Await method.
PS:使用上面的代码有时我会得到错误的数据
提前致谢
PS : with above code sometime I'm getting wrong data
Thanks in Advance
您也可以从 SerialPort.BaseStream 读取数据.它属于 Stream 类型,因此支持可等待的 ReadAsync() 方法.将其转换为字符串取决于您,请使用正确的编码.SerialPort 的默认值为 ASCIIEncoding.
You can also read data from SerialPort.BaseStream. Which is of type Stream so supports the awaitable ReadAsync() method. Converting it to a string is up to you, use the proper Encoding. The default for SerialPort is ASCIIEncoding.
这篇关于使用 Async await 方法从串口异步读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!