LaVOZs

The World’s Largest Online Community for Developers

'; multithreading - C# Windows Form - Serial Port problem / BackgroundWorker - LavOzs.Com

I developed a Windows Form application, using C#, that receives data through the serial port sent by a microcontroller. I'm receiving the data using the serialPort_DataReceived event in which I use ReadLine() to read the serial port. Then I use the Invoke method to call a function that will print the received string into a 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. 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. 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.

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. I'm still a noob in terms of programming Windows Form apps and even 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.

For more information check:

Related
Serial port communication: polling serial port vs using serial port DataReceived event
Thread used for Serial port data processing throwing “This BackgroundWorker is currently busy and cannot run multiple tasks concurrently”
c# serial port data loss
Managing serial ports in C#
C# BackgroundWorker and Com Port Problems
C# Async Serial Port Read
Serial port data received faster than handled
WinForms Serial port eats data