http://www.devx.com/tips/Tip/5573
The above post states that there will not be memory leak during object construction.
How about the code below? Will this cause any memory leaks? I see that the memory usage for the sample application increases slowly (in task manager) even after forcing the GC collection.
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Thread t = new Thread(Test);
t.Start();
}
bool b = true;
long i = 0;
void Test(object x)
{
while (b)
{
try
{
lock (this)
{
i++;
}
TestClass tt = new TestClass();
}
catch(Exception e)
{
}
GC.Collect();
GC.Collect();
GC.Collect();
GC.Collect();
GC.Collect();
GC.Collect();
}
}
private void timer1_Tick(object sender, EventArgs e)
{
lock (this)
{
Text = i.ToString();
}
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
lock (this)
{
b = checkBox1.Checked;
}
}
}
public class TestClass : UserControl
{
Button c = new Button();
public TestClass()
{
for (int i = 0; i < 1000; i++)
{
c.Paint += new PaintEventHandler(TestClass_Paint);
c.ParentChanged += new EventHandler(TestClass_ParentChanged);
c.PreviewKeyDown += new PreviewKeyDownEventHandler(TestClass_PreviewKeyDown);
}
// Throw the exception explicitly.
throw new Exception("Whaaaa?");
}
void TestClass_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
}
void TestClass_ParentChanged(object sender, EventArgs e)
{
}
void TestClass_Paint(object sender, PaintEventArgs e)
{
}
}
}