For example:
Queue<System.Drawing.SolidBrush> brushQ = new Queue<System.Drawing.SolidBrush>();
...
brushQ.Clear();
If I don't explicitly dequeue each item and dispose of them individually, do the remaining items get disposed when calling Clear()? How about when the queue is garbage collected?
Assuming the answer is "no", then what is the best practice? Do you have to always iterate through the queue and dispose each item?
That can get ugly, especially if you have to try..finally around each dispose, in case one throws an exception.
Edit
So, it seems like the burden is on the user of a generic collection to know that, if the items are Disposable (meaning they are likely to be using unmanaged resources that won't be cleaned up by the garbage collector), then:
Maybe the documentation for the generic collections should mention that.
The generic collections don't actually know anything about the type of object they contain, so calling Clear will not cause them to call Dispose() on the items. The GC will eventually dispose of them once the collection itself gets disposed of, provided nothing else has an active reference to one of those items.
If you want to ensure that the objects have their Dispose method called when you call Clear on the collection you would need to derive your own collection and override the appropriate methods and make the calls yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With