我试图在Windows 7,VS 2008上的多形式C#.Net应用程序中追逐内存泄漏。
我找到了这个SO帖子,表明应该自动调用第二个表格的终结者 this.Dispose() doesn't release memory used by Form after closing it. 但是,它对我不起作用。
每次弹出第二个表单(包含一个大字符串和一个PictureBox)时,即使我强制使用GC,应用程序使用的内存量也会增加。有趣的是,String的终结器IS被调用。 我在两个表单的Dispose方法中添加了一个日志; Form2的处理被称为。
代码是 Form1(主要表格)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace MemoryLeakTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
~Form1()
{
System.Diagnostics.Debugger.Log(0, "", "Form1.Destructor has been called.\n");
}
private void GC_Click(object sender, EventArgs e)
{
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
}
private void OpenForm_Click(object sender, EventArgs e)
{
Form secondForm = null;
if (secondForm == null)
{
secondForm = new Form2();
secondForm.Show();
}
secondForm = null;
}
private void UpdateMemory_Click(object sender, EventArgs e)
{
long memory = System.GC.GetTotalMemory(false);
this.MemoryUsage.Text = "Memory usage: " +
String.Format("{0:n}", memory) +
" bytes";
}
private void AllocateString_Click(object sender, EventArgs e)
{
// StringWrapper wrapper = new StringWrapper();
}
}
public class StringWrapper
{
String str = new String('*', 1024 * 1024);
~StringWrapper()
{
System.Diagnostics.Debugger.Log(0, "", "StringWrapper finalizer has been called.\n");
}
}
}
和Form2是
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace MemoryLeakTest
{
public partial class Form2 : Form
{
StringWrapper wrapper = new StringWrapper();
public Form2()
{
InitializeComponent();
this.pictureBox1.Image = Image.FromFile("C:/Windows/Web/Wallpaper/Windows/img0.jpg");
}
~Form2()
{
System.Diagnostics.Debugger.Log(0, "", "Form2.Finalizer has been called.\n");
}
}
}
我没有包含设计器生成的代码,但如果需要可以添加它