Does calling Clear disposes the items also?

半城伤御伤魂 提交于 2019-12-01 02:12:55
serhio

Q: Does?

A: No - Clear does not dispose the items (they could be used in other parts of your application).

So, if your ToolStripItems are standard .NET ones, should Clear be sufficient? After some reflection I'd say "probably not".

Yeah, this is true that if you will have any references to the ToolStripItem in other part of your application, the .NET GarbageCollector will destroy(use the class destructor) it automatically. But, it will not call the Dispose(true) method, that is, however, required for the form's IDisposable components.

Read a propos this and this.

Actually, I believe that you will, however, need to explicitly Dispose your Items, like the ToolStrip's Dispose method does (replace this by yourToolStrip):

if (!this.Items.IsReadOnly)
{
    for (int i = this.Items.Count - 1; i >= 0; i--)
    {
        this.Items[i].Dispose();
    }
    this.Items.Clear();
}

EDIT

I also created the following thread to clarify this question more generally.

You should rely on Dispose() call when you're dealing with unmanaged memory, shared resources or large memory areas. Doesn't seems this case.

Calling Clear doesn't dispose the items, but it removes the reference from the collection to the items. If that was the only reference to the items they will be garbage collected automatically at some point (which you can't predict, but you may control using the GC class).

I don't think so,more, it can cause many logical problems because you may have reference to that object in the collection for later use. If you don't have references to that objects Garbage Collector will dispose that objects later

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!