Why does IsDisposed return false after calling Dispose()?

I am trying to clear all items from a ToolStripDropDownButton. Since they are disposable, I call the dispose method on each of them. But I see that after calling the dispose() method, the IsDisposed property still returns false. Why is that and how can I check if Dispose() is called on any object ? It is not a problem (I hope) in my current project, but I would really like to know what is going on here...

my code so far :

private void ClearDropDownAccessConnections()
{
    ToolStripItem button = null;

    for (int i = toolStripDropDownButtonAccess.DropDownItems.Count - 1; i > 0; i--)
    {
        button = toolStripDropDownButtonAccess.DropDownItems[i] as ToolStripItem;
        if ((button.Tag != null) && ((int)button.Tag == 10))
        {
            toolStripDropDownButtonAccess.DropDownItems.Remove(button);
            button.Dispose();
            //IF I CHECk HERE THEN button.IsDisposed IS STILL FALSE                }
        }
    }

For whatever their reason, the original .NET developers have decided to flip the IsDisposed flag only if the disposed ToolStripItem has non-null Owner property (which you're kindly indirectly setting to null line before). This doesn't seem to have any further impact - ie you can assume the ToolStripItem is safely disposed despite this weird behaviour.

As for your broader question - the IDisposable interface does not provide any way of checking if the object was disposed (and to make matters worse - classes implementing it do not have to guarantee an exception-free execution if it's called more than once (see MSDN)). You need to rely on the developers of said classes to provided some info if the object was actually disposed (which as can be seen in the ToolStripItem example is not a fool proof method), or track this somehow in your code.

Having said all that, it rarely becomes a problem in real-life scenarios (though it's useful to be aware of it).

链接地址: http://www.djcxy.com/p/78872.html

上一篇: 如何访问Galaxy S5温度传感器?

下一篇: 为什么调用Dispose()后IsDisposed返回false?