SerialPort.BytesToRead And System.StackOverflowException

Just sharing, no big deal.

This applies to MS .NET Programming and MS Windows Platform.

When invoking 'SerialPort.BytesToRead' to check for available bytes from the input buffer, one may encounter 'System.StackOverflowException'.

Don't worry, this is common issue.

'System.StackOverflowException' is an exception which was resulted having too many calls to a method within a short period of time. This is especially common when dealing with recursive calls.

The solution is not to slow down communication with the serial port by having longer delays in between read and write operation, but to reduce the speed of invoking 'SerialPort.BytesToRead' during read process. To do this, introduce deliberate delay if the data is not completely received or when there is no data yet. Let's call this 'stackoverflow delay'. Basically, the idea is to make longer the duration in between invokes of 'SerialPort.BytesToRead' property.

What this means is let's say you have a loop. For each iteration, you will evaluate 'SerialPort.BytesToRead' to check whether there are still data available, if not then you will quit the loop. In between each iteration, introduce this so called 'stackoverflow delay' via deliberate wait. You can make use of System.Threading.Thread.Sleep, so that 'SerialPort.BytesToRead' actually have got enough time to rest before the next invocation.

Introducing the 'stackoverflow delay' is a also a good way to reduce wasted loop, which is to reduce CPU utilization.

Besides that, this exception will actually crash the application all together. It cannot be captured even with implementation of handling for AppDomain.CurrentDomain.UnhandledException.

Also refer to
  1. How to reduce CPU Utilization (Windows Software Development) ?
  2. Troubleshoot CPU Utilization Using Profiler (Windows Software Development)

Comments