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

C# 在没有内存泄漏的情况下清除ListView项,c#,.net,winforms,C#,.net,Winforms,在控件的控件上使用Clear()方法(除非它们在别处引用并在那里得到处理)。解决办法是 但是,无法处理ListView的项和。这是否意味着使用ListView的项“Clear()”也没有内存泄漏?如果没有-如何避免内存泄漏?将它们设置为null是否足够?(如果需要的话) 编辑(澄清问题) 控件控件的问题在于,当控件Clear()ed时,会创建对它们的额外“引用”(请参见上面的第一个链接)。由于列表视图是一个控件,我想知道它的项是否也会发生同样的情况,或者,由于它们不是控件,是否不存在这样的问题。

在控件的控件上使用
Clear()
方法(除非它们在别处引用并在那里得到处理)。解决办法是

但是,无法处理ListView的项和。这是否意味着使用ListView的项“
Clear()
”也没有内存泄漏?如果没有-如何避免内存泄漏?将它们设置为null是否足够?(如果需要的话)

编辑(澄清问题)


控件控件的问题在于,当控件
Clear()
ed时,会创建对它们的额外“引用”(请参见上面的第一个链接)。由于
列表视图
是一个控件,我想知道它的
是否也会发生同样的情况,或者,由于它们不是控件,是否不存在这样的问题。

这一切都归结于所有权。如果没有其他人引用这些项目,您将需要正确处理这些项目

方法是从项目列表中删除这些项目,并检查每个项目是否实现IDisposable,然后将其丢弃

while (listBox.Items.Count > 0)
{
    var item = listBox.Items[listBox.Items.Count -1);
    listBox.Items.RemoveAt(listBox.Items.Count -1);
    if (item is IDisposable)
    {
        ((IDisposable)item).Dispose();
    }

}

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

这是反映的
Control.Dispose()

    /// <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);
    }
它指的是

/// <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;
    }
///销毁与控件关联的句柄。
[EditorBrowsable(EditorBrowsableState.Advanced)]
[UIPermission(SecurityAction.LinkDemand,Window=UIPermissionWindow.AllWindows),SecurityPermission(SecurityAction.InheritanceDemand,Flags=SecurityPermissionFlag.UnmanagedCode)]
受保护的虚拟句柄()
{
if(this.RecreatingHandle&&this.threadCallbackList!=null)
{
锁定(此.threadCallbackList)
{
if(Control.threadCallbackMessage!=0)
{
NativeMethods.MSG MSG=默认值(NativeMethods.MSG);
if(unsafentiveMethods.PeekMessage(ref mSG,new HandleRef(this,this.Handle),Control.threadCallbackMessage,Control.threadCallbackMessage,0))
{
此.SetState(32768,真);
}
}
}
}
如果(!this.RecreatingHandle&&this.threadCallbackList!=null)
{
锁定(此.threadCallbackList)
{
Exception Exception=新的ObjectDisposedException(base.GetType().Name);
而(this.threadCallbackList.Count>0)
{
Control.ThreadMethodEntry ThreadMethodEntry=(Control.ThreadMethodEntry)this.threadCallbackList.Dequeue();
threadMethodEntry.exception=异常;
threadMethodEntry.Complete();
}
}
}
if((64&(int)((long)unsafentiveMethods.GetWindowLong(newhandleref(this.window,this.InternalHandle),-20))!=0)
{
unsafentiveMethods.DefMDIChildProc(this.InternalHandle,16,IntPtr.Zero,IntPtr.Zero);
}
其他的
{
this.window.DestroyHandle();
}
this.trackMouseEvent=null;
}
DestroyHandle
是销毁控件句柄的实际方法,但该控件可能有更多非托管句柄,如您在
Dispose
中看到的,它首先销毁
PropBackbrash的句柄

正如您所看到的,
Control
处理非托管内存。如果
ListView
中的项不包含任何非托管内存,则无需担心它,因为
GC
将处理它

如果项目包含非托管内存,则必须单独处理每个项目,最好让它们继承
IDisposable
,然后在手动时调用
Dispose
。如果您不想在每次清除列表时循环浏览项目,可以创建一个扩展方法来为您执行此操作


以上内容主要与自定义的
ListView
控件相关,在该控件中,您可以根据对象自己呈现
ListView
。NET中的标准
ListViewItem
不存储非托管内存,因此
GC
ListView
清除项目和/或处理项目时负责内存。

考虑到C有垃圾收集,实际上它与对这些项目的引用无关。这与它们是否具有非托管资源(例如句柄)有关。此外,该问题与
列表视图
有关,其中的项目不是
对象
,而是
列表视图项目
谢谢。但是控件控件的问题是,当它们被清除()时,会创建一个对它们的额外引用(请参阅我问题中的第一个链接)。由于ListView是一个控件,我想知道它的
项是否也会发生同样的情况,或者,由于它们不是控件,是否不存在这样的问题。我不相信有任何额外的引用
/// <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;
    }