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:
Maybe the documentation for the generic collections should mention that.
When do you expect them to be disposed? How will the collection know if there are other references to the objects in it?
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.
Let me see if I can write an example code for this one.
Edit:
The following code implements an IDisposable Queue:
class DisposableQueue<T>:Queue<T>,IDisposable where T:IDisposable
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public virtual void Dispose(bool disposing) {
if (disposing) {
foreach (T type in this) {
try
{
type.Dispose();
}
finally {/* In case of ObjectDisposedException*/}
}
}
}
#endregion
}
链接地址: http://www.djcxy.com/p/54454.html