【问题标题】:Reading from serial port asynchronously using Async await method使用 Async await 方法从串口异步读取
【发布时间】:2013-09-19 20:34:06
【问题描述】:

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

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:使用上面的代码有时我会得到错误的数据
提前致谢

【问题讨论】:

  • 抱歉,SO 不是“为我编写代码”网站。了解更多关于async-await 的信息(我假设您目前还不太了解),然后尝试自己编写代码。如果它不起作用,请回到这里并提出问题。

标签: c# asynchronous serial-port async-await c#-5.0


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2019-01-17
    • 2017-05-13
    • 2014-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-10
    • 1970-01-01
    • 2016-09-27
    相关资源
    最近更新 更多