我正在编写一个程序来模拟一个通过串口传输数据的设备。为此,我在我的表单中创建了一个 System.IO.Ports.SerialPort 对象,并创建了一个 System.Windows.Forms.Timer 来以给定的频率进行传输。一切正常,除了当频率接近串行端口速度的极限时,它开始锁定 UI 并最终在数据发送速度快于端口数据速度时变得无响应。我的代码是:
private void OnSendTimerTick(object sender, EventArgs e)
{
StringBuilder outputString = new StringBuilder("$", 51);
//code to build the first output string
SendingPort.WriteLine(outputString.ToString());
outputString = new StringBuilder("$", 44);
//code to build the second output string
SendingPort.WriteLine(outputString.ToString());
if (SendingPort.BytesToWrite > 100)
{
OnStartStopClicked(sender, e);
MessageBox.Show("Warning: Sending buffer is overflowing!");
}
}
我原以为 WriteLine 函数是异步的 - 当端口在后台传输时立即返回。相反,似乎 OnSendTimerTick 函数已正确线程化,但 WriteLine 似乎在 UI 线程中运行。
如何让串行端口以这种方式运行?在定时器中创建 SerialPort 对象似乎是个坏主意,因为那样我就必须在每个定时器滴答时打开和关闭它。
最佳答案
它只是部分异步,它会立即返回,但前提是您写入的字节适合串行端口驱动程序的传输缓冲区。当您用太多数据淹没端口,速度快于传输速度时,这将戛然而止。您可以使用 SerialPort.BaseStream.BeginWrite() 方法使其真正异步。这不会让它变得更快,但会将瓶颈移到其他地方,可能远离 UI。
关于c# - 如何在 .NET 中通过串行端口异步传输?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8014596/