c# - 在没有内存泄漏的情况下清除 ListView 项

标签 c# .net winforms

在控件的 Control 上使用 Clear() 方法 causes a memory leak (除非它们在别处被引用并在那里得到处理)。解决方法是Dispose of those child Controls instead of Clear()ing them .

但是,ListViews 的项目 are not Controls并且无法处理掉。这是否意味着使用 ListView 的 Items 的 Clear() 也没有内存泄漏?如果不是——如何避免内存泄漏?将它们设置为 null 就足够了吗? (如果,也就是说,根本需要它)

编辑(澄清问题)

Controls 控件的问题是当它们被 Clear()ed 时,会创建对它们的额外“引用”(参见上面的第一个链接)。由于 ListView 控件,我想知道它的 Items 是否也会发生同样的情况,或者是否因为它们不是 控件 - 不存在此类问题。

最佳答案

好吧,根据文档,Clear 不会处理控制句柄,这是您必须手动执行的操作。句柄是非托管的,您可以通过 Control.Handle 访问它们,这将返回单个控件的非托管句柄。在控件上调用 Dispose 将释放非托管句柄。

这是 Control.Dispose() 反射(reflect)出来的。

    /// <summary>Releases the unmanaged resources used by the <see cref="T:System.Windows.Forms.Control" /> and its child controls and optionally releases the managed resources.</summary>
    /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources. </param>
    protected override void Dispose(bool disposing)
    {
        if (this.GetState(2097152))
        {
            object @object = this.Properties.GetObject(Control.PropBackBrush);
            if (@object != null)
            {
                IntPtr intPtr = (IntPtr)@object;
                if (intPtr != IntPtr.Zero)
                {
                    SafeNativeMethods.DeleteObject(new HandleRef(this, intPtr));
                }
                this.Properties.SetObject(Control.PropBackBrush, null);
            }
        }
        this.UpdateReflectParent(false);
        if (disposing)
        {
            if (this.GetState(4096))
            {
                return;
            }
            if (this.GetState(262144))
            {
                throw new InvalidOperationException(SR.GetString("ClosingWhileCreatingHandle", new object[]
                {
                    "Dispose"
                }));
            }
            this.SetState(4096, true);
            this.SuspendLayout();
            try
            {
                this.DisposeAxControls();
                ContextMenu contextMenu = (ContextMenu)this.Properties.GetObject(Control.PropContextMenu);
                if (contextMenu != null)
                {
                    contextMenu.Disposed -= new EventHandler(this.DetachContextMenu);
                }
                this.ResetBindings();
                if (this.IsHandleCreated)
                {
                    this.DestroyHandle();
                }
                if (this.parent != null)
                {
                    this.parent.Controls.Remove(this);
                }
                Control.ControlCollection controlCollection = (Control.ControlCollection)this.Properties.GetObject(Control.PropControlsCollection);
                if (controlCollection != null)
                {
                    for (int i = 0; i < controlCollection.Count; i++)
                    {
                        Control control = controlCollection[i];
                        control.parent = null;
                        control.Dispose();
                    }
                    this.Properties.SetObject(Control.PropControlsCollection, null);
                }
                base.Dispose(disposing);
                return;
            }
            finally
            {
                this.ResumeLayout(false);
                this.SetState(4096, false);
                this.SetState(2048, true);
            }
        }
        if (this.window != null)
        {
            this.window.ForceExitMessageLoop();
        }
        base.Dispose(disposing);
    }

如您所见,它释放了非托管处理程序。这就是 Dispose() 通常用于或进一步阐述您通常实现 IDisposable 接口(interface)的原因。

让我们在 Dispose 中进一步挖掘,您会注意到这部分。

this.DestroyHandle();

指的是

/// <summary>Destroys the handle associated with the control.</summary>
    [EditorBrowsable(EditorBrowsableState.Advanced)]
    [UIPermission(SecurityAction.LinkDemand, Window = UIPermissionWindow.AllWindows), SecurityPermission(SecurityAction.InheritanceDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
    protected virtual void DestroyHandle()
    {
        if (this.RecreatingHandle && this.threadCallbackList != null)
        {
            lock (this.threadCallbackList)
            {
                if (Control.threadCallbackMessage != 0)
                {
                    NativeMethods.MSG mSG = default(NativeMethods.MSG);
                    if (UnsafeNativeMethods.PeekMessage(ref mSG, new HandleRef(this, this.Handle), Control.threadCallbackMessage, Control.threadCallbackMessage, 0))
                    {
                        this.SetState(32768, true);
                    }
                }
            }
        }
        if (!this.RecreatingHandle && this.threadCallbackList != null)
        {
            lock (this.threadCallbackList)
            {
                Exception exception = new ObjectDisposedException(base.GetType().Name);
                while (this.threadCallbackList.Count > 0)
                {
                    Control.ThreadMethodEntry threadMethodEntry = (Control.ThreadMethodEntry)this.threadCallbackList.Dequeue();
                    threadMethodEntry.exception = exception;
                    threadMethodEntry.Complete();
                }
            }
        }
        if ((64 & (int)((long)UnsafeNativeMethods.GetWindowLong(new HandleRef(this.window, this.InternalHandle), -20))) != 0)
        {
            UnsafeNativeMethods.DefMDIChildProc(this.InternalHandle, 16, IntPtr.Zero, IntPtr.Zero);
        }
        else
        {
            this.window.DestroyHandle();
        }
        this.trackMouseEvent = null;
    }

DestroyHandle 是销毁控件句柄的实际方法,但控件可能有更多非托管句柄,如您在 Dispose 中看到的那样,它首先销毁句柄PropBackBrush 的。

如您所见,Control 处理非托管内存。如果 ListView 中的项目不包含任何非托管内存,那么您无需担心,因为 GC 会处理它。

如果项目包含非托管内存,那么您将不得不单独处理每个项目,最好让它们继承 IDisposable,然后手动调用 Dispose。如果您不想在每次清除列表时都循环遍历这些项目,您可以创建一个扩展方法来为您完成这项工作。

以上主要与自定义 ListView 控件相关,您可以在其中根据对象自行呈现 ListView。 .NET 中的标准 ListViewItem 不存储非托管内存,因此 GCListView 清除项目和/或者当它被处置时。

关于c# - 在没有内存泄漏的情况下清除 ListView 项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32203245/

相关文章:

c# - 在特定位置向内容类型添加字段

.net - 有没有办法静默或自动安装 .NET?

.net - ping 网络服务器以查看是否运行/事件的简单方法?

MySQL 查询(求和)在 VB 中不起作用

winforms - 如何使用SaveFileDialog将stringbuilder的内容保存到文本文件?

c# - 在 ASP.NET 服务器端验证 Recaptcha 2(无验证码 reCAPTCHA)

c# - 从 XDocument 获取 XmlElement

winforms - 如何实现ScintillaNET列编辑模式

c# - 我什么时候应该使用并行 foreach 以及什么时候应该使用并行 linq?

c# - "this file is blocked because it came from another computer"- ajax 权限问题