Why does IsDisposed return false after calling Dispose ()?

I am trying to clear all items from 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 this and how can I check if Dispose () is being called on any object? This is not a problem (I hope) in my current project, but I would really like to know what is happening here ...

my code is:

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 } } } 
+7
c # winforms dispose
source share
1 answer

For some reason, the original .NET developers decided to flip the IsDisposed flag only if the available ToolStripItem has a non-null Owner property (which you indirectly set to null before). This, apparently, has no influence, i.e. You can assume that ToolStripItem safely deleted, despite this strange behavior.

As for your broader question - the IDisposable interface does not provide any way to check if an object has been deleted (and, even worse), classes implementing it should not guarantee perfect execution if it is called more than once (see MSDN )). You should rely on the developers of the specified classes to provide some information if the object was actually deleted (which, as you can see from the ToolStripItem example, is not a method of proving a fool) or track it somehow in your code.

Having said all this, it rarely becomes a problem in real-world scenarios (although it is useful to know about it).

+4
source share

All Articles