简体   繁体   English

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

[英]Reading from serial port asynchronously using Async await method

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

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. 我们知道这种API称为基于事件的异步模式(EAP),我想使用Async Await方法编写上面的代码。

PS : with above code sometime I'm getting wrong data PS:有时上面的代码,我得到错误的数据
Thanks in Advance 提前致谢

You can also read data from SerialPort.BaseStream. 您还可以从SerialPort.BaseStream中读取数据。 Which is of type Stream so supports the awaitable ReadAsync() method. 这是Stream类型,因此支持等待的ReadAsync()方法。 Converting it to a string is up to you, use the proper Encoding. 将其转换为字符串取决于您,使用正确的编码。 The default for SerialPort is ASCIIEncoding. SerialPort的默认值是ASCIIEncoding。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM