简体   繁体   English

C#Windows窗体-串行端口问题/ BackgroundWorker

[英]C# Windows Form - Serial Port problem / BackgroundWorker

I developed a Windows Form application, using C#, that receives data through the serial port sent by a microcontroller. 我使用C#开发了Windows Form应用程序,该应用程序通过微控制器发送的串行端口接收数据。 I'm receiving the data using the serialPort_DataReceived event in which I use ReadLine() to read the serial port. 我正在使用serialPort_DataReceived事件接收数据,在该事件中,我使用ReadLine()来读取串行端口。 Then I use the Invoke method to call a function that will print the received string into a textBox. 然后,我使用Invoke方法调用一个函数,该函数会将接收到的字符串打印到textBox中。 The problem is that the app can't keep up with the rate at which it receives the strings, for example, the string that I send from the microcontroller has the time at which it was sent and even though it has already passed 2 or 3 seconds the app is still printing the strings that were sent at the 0.2 second. 问题是应用程序无法跟上接收字符串的速度,例如,我从微控制器发送的字符串具有发送时间,即使它已经通过了2或3秒后,应用程序仍会打印在0.2秒发送的字符串。 And when I send a string to the microcontroller to stop sending data, the app onlys stops ptinting the data after a while, this is, it keeps printing the values stored in the receiving buffer. 当我向微控制器发送字符串以停止发送数据时,该应用程序仅会在一段时间后停止打印数据,这就是说,它会继续打印存储在接收缓冲区中的值。

I believe that is happens given the large amount of data that the app receives and the rate (I'm using a baud rate of 115200), one string for every millisecond. 我认为,考虑到应用程序收到的大量数据和速率(我使用的波特率为115200),即每毫秒发送一个字符串,这种情况会发生。 This is, I think that the app is always being interrupted by the DataReceived event and it doesn't has time to print the data and starts falling behind. 这是因为,我认为该应用程序始终被DataReceived事件中断,并且它没有时间打印数据并开始落后。

One way I though of overcome this problem was with multi-threading but I can't figure it out how. 我克服这个问题的一种方法是使用多线程,但是我不知道该怎么做。 I already tried a few examples using the BackgroundWorker but I didn't manage to make it work at all. 我已经使用BackgroundWorker尝试了一些示例,但是我根本没有使其工作。 I'm still a noob in terms of programming Windows Form apps and even C#. 就Windows Form应用程序甚至C#而言,我还是一个菜鸟。

Can anyone confirm the cause of the problem? 谁能确认问题的原因? And how do I make a thread to print the received data? 以及如何使线程打印接收到的数据?

You can utilize SerialPort.ReceivedBytesThreshold property and SerialPort.ReadExisting() method (or a StringBuilder instance) to update UI with a batch of strings at once rather than a single string. 您可以利用SerialPort.ReceivedBytesThreshold属性和SerialPort.ReadExisting()方法(或StringBuilder实例)来一次更新一批批字符串而不是单个字符串的UI。

For more information check: 有关更多信息,请检查:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM