使用异步await方法从串行端口异步读取 [英] Reading from serial port asynchronously using Async await method

查看:197
本文介绍了使用异步await方法从串行端口异步读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于使用异步await方法从串行端口异步读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆