I've got a bunch of IDisposable
objects in a lookup table (plain old Dictionary<>, right now), but to simplify the code and avoid error's I'm looking for a collection class which "owns" the items it holds, and to avoid reinventing the wheel - does such a class already exist?
The specification should be that:
- The collection must be disposable, and when it is disposed all contained items should be disposed too.
- Whenever an item is removed, it is Dispose()
-d first.
- ideally, the collection would be generic with the type constraint enforcing the IDisposable
-ness of the contained type.
I sorta doubt such a class exists, but I've been pleasantly surprised by the existence of ReadOnlyCollection
and ObservableCollection
before...
Essentially, I'd like the equivalent of the C++ STL containers but then for the CLR ;-).
Typically, types that use unmanaged resources implement the IDisposable or IAsyncDisposable interface to allow the unmanaged resources to be reclaimed. When you finish using an object that implements IDisposable, you call the object's Dispose or DisposeAsync implementation to explicitly perform cleanup.
IDisposable is an interface that contains a single method, Dispose(), for releasing unmanaged resources, like files, streams, database connections and so on.
By default, the garbage collector automatically calls an object's finalizer before reclaiming its memory. However, if the Dispose method has been called, it is typically unnecessary for the garbage collector to call the disposed object's finalizer.
If you access unmanaged resources (e.g. files, database connections etc.) in a class, you should implement IDisposable and overwrite the Dispose method to allow you to control when the memory is freed.
You're looking for CompositeDisposable.
using System.Reactive.Disposables;
...
CompositeDisposable xs = new CompositeDisposable(Disposable.Empty);
xs.Add(Disposable.Empty);
xs.Add(Disposable.Empty);
xs.Dispose();
From what I know, there is only exits such collection for IComponents - Container implements IContainer. For generic IDisposable I think you have no other options but "reinvent the wheel".
Remember that your collection might not be the only one containing the disposable objects ... What if another object (external to the collection) is referencing one of those? If you dispose it when the collection is disposed, then what would happen to the object?
If these objects implement IDisposable
for some unmanaged resources cleaning then make sure they implement finalization as well and dispose of unmanaged resources there.
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