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

Reading from serial port asynchronously using Async await method(使用 Async await 方法从串口异步读取)
本文介绍了使用 Async 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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)