使用Async await方法异步读取串行端口

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

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。