【发布时间】: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