winform应用程序中存在内存泄漏的常见问题是什么?

时间:2011-10-08 19:23:12

标签: winforms memory-leaks memory-profiling

我试着去掌握Ants Memory Profiler。我遇到的问题是我没有一个容易出现内存泄漏的应用程序。

我使用了Redgate(QueryBee)的样本,但这是为了我的口味。必须有一个更简单的应用程序。

我尝试制作一个,但它不起作用。它不工作意味着:我没有内存泄漏。我读到关于调用ShowDialog而不处理被调用的表单会让我发生内存泄漏,但事实并非如此。

我使用VS2010和.NET 4.0

我对非常​​普遍的问题特别感兴趣。

这是我到目前为止。你能让我得到内存泄漏吗?:

的MainForm

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 MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SubForm formToCall = new SubForm();
            formToCall.ShowDialog();
        }
    }
}

子窗体

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;
using System.Collections;

namespace MemoryLeakTest
{
    public partial class SubForm : Form
    {


        public SubForm()
        {
            InitializeComponent();
        }

        private void SubForm_Load(object sender, EventArgs e)
        {

            ArrayList persons = new ArrayList();

            for (int i = 0; i <= 50000; i++)
            {
                var person = new {
                    Name = "1 SchorschSchorschSchorschSchorschSchorschSchorschSchorschSchorschSchorschSchorschSchorschSchorschSchorsch",
                    LastName = "KluniKluniKluniKluniKluniKluniKluniKluniKluniKluniKluniKluniKluniKluniKluniKluniKluniKluniKluniKluni", 
                    Age = 50,
                    City = "LondonLondonLondonLondonLondonLondonLondonLondonLondonLondonLondonLondonLondonLondonLondonLondonLondonLondonLondonLondonLondon",
                    Zip = "223012230122301223012230122301223012230122301223012230122301223012230122301223012230122301223012230122301223012230122301223012230122301", 
                    Index = i 

                };
                persons.Add(person);
            }

            dataGridView1.DataSource = persons;
        }

        private void SubForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            //this.Dispose();
        }


    }
}

1 个答案:

答案 0 :(得分:1)

将此添加到您的SubForm

public void mouse_handler(object sender, MouseEventArgs e)
{

}

并更改MainForm以执行此操作

private void button1_Click(object sender, EventArgs e)
{
     SubForm formToCall = new SubForm();
     this.MouseClick += new MouseEventHandler(formToCall.mouse_handler);
     formToCall.ShowDialog();
}

现在无论你是否。(无论是否分配SubForm),你仍然会有“泄密”。您的MainForm通过其鼠标事件处理程序无限期地保留对SubForms的引用,该处理程序基本上只是一个接收事件的人员列表,因为该处理程序永远不会被注销。

蚂蚁会帮助你追踪这个,而不是手动,它会向你展示仍然活着并从根引用的对象,你必须发现这些对象不应该在任何地方被引用。我相信蚂蚁也会产生警告/等等。当它找到已经.Disposed()的对象,但仍在某处被引用时。

相关问题