In my application, I have a lot of RichTextBoxes that are created dynamically in run time. I realized that the application has a memory leak, which is caused by the RichTextBox controls. To prove that the memory leaks because of the control I wrote the following test method:
for (int i = 0; i < 3000; i++)
{
Control rich = new RichTextBox();
pnl.Content = rich;
}
GC.Collect();
GC.WaitForPendingFinalizers();
pnl is a ContentControl that is declared in Xaml code.
If you run the following code, you can see that the memory usage is growing rapidly.
Any ideas how to solve the problem?
I considered creating an object pool, but this would complicate my application, and I rather avoid it.
edit: I’ve added call to the garbage collector to demonstrate that the objects are not garbage collected – there is no improvement in the memory usage with and without the call to the GC collect method.
Note that calling rich.Dispose within the loop eliminates the memory usage growth.
Found this elsewhere, and it seems to be correct as far as my testing is concerned.
So the RichTextBox (or FlowDocument) in case is not leaking just waiting on a background thread to cleanup. When it runs exactly who knows. I wish this just implemented a dispose method that would force a cleanup immediately.