StackOverflow with ListBox or ListView
I have been writing some multi-threaded code recently where I was initially adding items to the .NET ListBox control and then later changed to the ListView control. In both cases, my code would get a StackOverflowException fairly consistently when I added the 224th item (my first two items were added manually, so it was the 222nd item added via a separate thread). The first troubleshooting tip is that it does not have an infinite loop, which I could confirm was not the case.
So the first thing I tried was to limit the number of items added with each button click. Doing this allowed me to go well over the 224/222 limit from before—thus eliminating any thoughts of a limit on the number of items the controls could handle.
After some other failed tests, I found out the issue was in my cross-thread communication. Specifically, I had a separate thread adding items to a control created on the application's main thread. To handle cross-thread communication, I kept calling _this.BeginInvoke_, but I never called _this.EndInvoke_—something many places seem to claim is unnecessary. However, at some point, it will fail with the StackOverflowException—that point is dependent on several factors (with the worst factor of all being timing), making this one of those issues that may only appear in the field.
My solution was simple: replace the standard _this.Invoke_ method (instead of BeginInvoke), and the issue disappeared.
For search engines, the full exception is: “An unhandled exception of type 'System.StackOverflowException' occurred in System.Windows.Forms.dll.”