Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If a generic collection is instantiated to contain iDisposable items, do the items get disposed?

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:

  1. When you remove an item from the collection, make sure you Dispose() it.
  2. DON'T CALL Clear(). Iterate through the collection and dispose of each item.

Maybe the documentation for the generic collections should mention that.

like image 588
mbeckish Avatar asked Dec 23 '22 13:12

mbeckish


1 Answers

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.

like image 197
Scott Dorman Avatar answered Feb 01 '23 22:02

Scott Dorman