写了个程序,由于动态New出来的对象比较多,被发现有少量的内存泄露问题。仔细找了好几圈,确认所有引用都被释放了,但问题依然存在。后来仔细观察发现,即使是一个简单的按钮事件:鼠标移进去变色,移出来恢复原来的颜色,这样的情况下内存也会持续增长,尽管增长幅度不尽相同。

于是写了个简单的测试程序,有两个按钮:点击Add按钮,动态new出8000个Ellipse,大小为10*10,半透明;点击Delete按钮,从界面上移除这8000个Ellipse,使用Children.Clear()方法。经测试发现,每次Add以后,再Delete,内存只有极少量的回收(估计是从界面渲染上回收的),而每次Add之后内存增长都在10兆到20兆。测试代码如下:

public void Page_Loaded(object o, EventArgs e)
{
// Required to initialize variables
InitializeComponent();

addNew.MouseLeftButtonUp += new MouseEventHandler(addNew_MouseLeftButtonUp);
delAll.MouseLeftButtonUp += new MouseEventHandler(delAll_MouseLeftButtonUp);
}

void delAll_MouseLeftButtonUp(object sender, MouseEventArgs e)
{
t.Children.Clear();
t.Children = new VisualCollection();
}

void addNew_MouseLeftButtonUp(object sender, MouseEventArgs e)
{
for (int i = 0; i < 8000; i++)
{
Ellipse elps = new Ellipse();
elps.Fill = new SolidColorBrush(Color.FromArgb((byte)99, (byte)00, (byte)00, (byte)00));
elps.Width = 10;
elps.Height = 10;
elps.SetValue(Canvas.LeftProperty, (i % 53) * 12);
elps.SetValue(Canvas.TopProperty, (i / 53) * 12);
t.Children.Add(elps);
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.