I've been working on a data export program that's extracting a bunch of records from a database. One of the steps involves converting an RTF text string into plain text and this ended up causing a memory leak of User Objects when it ran. One of the columns that Task Manager will show is "USER objects" - when this hits ~10,000 the program will run out of allocation space and the program faults with "error creating window handle"
This was happening because I wasn't disposing of my object at the end of the method.
My question is, why didn't C#/.net dispose of it for me?
Here's a quick sample of code that will reproduce the leak. Put the code into a Winforms application and push the button to get it to loop through the memory waster.
private void wasteMemory()
{
System.Windows.Forms.RichTextBox rtfBox = new System.Windows.Forms.RichTextBox();
//RTF text that reads "Hello World"
rtfBox.Rtf = "{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1033{\\fonttbl{\\f0\\fnil\\fcharset0 Arial;}} {\\colortbl ;\\red0\\green0\\blue0;} \\viewkind4\\uc1\\pard\\cf1\\fs29 Hello World} ";
//If line below is commented out, User Objects grow out of control.
//rtfBox.Dispose();
}
private void button1_Click(object sender, EventArgs e)
{
for (int i = 1; i < 100000; i++)
{
wasteMemory();
}
}
It's my understanding that the scope of a method any objects created in side of it are disposed of when the method completes. I expected the rtfBox to be disposed of, but it doesn't.