StackOverflow with ListBox or ListView

Submitted by Robert MacLean on Mon, 01/04/2010 - 15:09

Clipboard013 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 I would get a StackOverflow exception fairly consistently when I added the 224th item (my first two items I added manually so it was the 222nd item added via a separate thread). The first troubleshooting tip is that you do not have an infinite loop, which I could confirm that it did not have.

So the first thing I tried, was to limit the number of items which would be added with each button click. Doing this enabled me to go well over the 224/222 limit from before – thus eliminating any thoughts of limit on the number of items the controls could handle.

After some other failed tests I found out it was how I was handling the cross thread communication, being that I had a separate thread add the items to the control which was created on the applications main thread. To handle to cross threaded communication I kept calling this.BeginInvoke, however I never called this.EndInvoke which a lot of places seem to say it is fine. However at some point it will fail, with the StackOverflow exception – that point is dependant on a number of factors (including the worst factor of all: timing, making this one of those issues that may only appear in the field).

My solution was simple, change the standard this.Invoke method and the issue went away.

For the search engines the full exception is “An unhandled exception of type 'System.StackOverflowException' occurred in System.Windows.Forms.dll”.