Serial port reads asynchronously using Async wait method

I use this method to read from the 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); } 

as we know. This type of API is called an event-based asynchronous pattern (EAP), I want to write the code above using the Async Await method.

PS: with the previous code I get invalid data
Thanks at Advance

+4
source share
1 answer

You can also read data from SerialPort.BaseStream. Which is of type Stream, therefore it supports the expected ReadAsync () method. Converting it to a string is up to you, use the correct encoding. By default, SerialPort uses ASCIIEncoding.

+12
source

Source: https://habr.com/ru/post/1502292/


All Articles