I've been running into a kinda frustrating roadblock with RichTextBox.ScrollToCaret. I have code that prints messages to a RichTextBox. When each message is sent to the form, it is split into multiple lines and formatted, then each line is concatenated and the result is sent to RichTextBox.Append. Then, the following two calls are made to scroll to the bottom of the box:
outputBox.Select(outputBox.Text.Length, 0);
outputBox.ScrollToCaret();
When printing one message, it's fine. When printing a small handful of messages, no problems. When printing a bunch of messages in quick succession, it will randomly (how many messages it prints before it happens) throw an AccessViolationException ("Attempted to read or write protected memory. This is often an indication that other memory is corrupt.", full details here) the next time Append is called on that box to add the next message. This only happens when doing it in quick succession and only when using RichTextBox.ScrollToCaret each time. The following code that I fell back on works fine:
outputBox.Focus();
outputBox.Select(outputBox.Text.Length, 0);
I found out too that even if I caught the exception and threw it away, the program will hang on the next invocation of Append. So, I assume it's a problem with the actual code in RichTextBox. Anyone have any ideas?
I can post more of my code if anyone needs it but the situation really is pretty basic. A few things of note is that there is no multithreading (other than the inherent UI thread), so the object sending the messages and the form receiving them are on the same thread. Also, this is under .NET 4.0.
I found this other question addressing this issue but only a workaround was provided, no real explanation: AccessViolation occurs in RichTextBox.ScrollToCaret. My experience with threading is unfortunately not where I'd want so I wasn't able to get their solution working properly, but luckily what I posted above works just fine.
Update 1
So it looks after some testing like it has something to do with XNA, so it may be my misunderstanding of how that works with threading. I have been unable to reproduce the error in a pure WinForms app, but easily accomplished it with a simple XNA game. I have zipped both here for you to look at. Apologies for the error. https://dl.dropbox.com/u/16985121/StackOverFlowExamples.zip