0

我尝试使用 Ants Memory Profiler 来掌握。我遇到的问题是我没有一个简单的应用程序存在内存泄漏。

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

我试图弥补一个,但它不工作。它不起作用意味着:我没有内存泄漏。我读到了调用 ShowDialog 而不处理被调用的表单会让我发生内存泄漏,但这里不是这种情况。

我使用 VS2010 和 .NET 4.0

我对非常常见的问题特别感兴趣。

这是我到目前为止所拥有的。你能给我一个内存泄漏吗?:

主窗体

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();
        }


    }
}
4

1 回答 1

1

将此添加到您的子表单

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();
}

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

Ants 将帮助您追踪这一点,但不是手动的,它会向您显示对象仍然处于活动状态并从根目录引用,并且您必须发现这些对象不应在任何地方引用。我相信蚂蚁也可以产生警告/等。当它找到已被 .Disposed() 处理但仍被某处引用的对象时。

于 2011-10-08T19:44:27.327 回答