[英]Reading from serial port asynchronously using Async await method
我用這種方式從串口讀取:
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:有時上面的代碼,我得到錯誤的數據
提前致謝
您還可以從SerialPort.BaseStream中讀取數據。 這是Stream類型,因此支持等待的ReadAsync()方法。 將其轉換為字符串取決於您,使用正確的編碼。 SerialPort的默認值是ASCIIEncoding。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.