If you want to deterministically manage objects in a collection, you should call Dispose for each:
myImages.ToList().ForEach(image => image.Dispose());
If you do not, and if your objects become inaccessible, the GC will eventually launch and release them.
Now, if you do not want to manually code Dispose calls, you can create a wrapper class that implements IDisposable and use it in the using statement:
using (myImages.AsDisposable()) {
This is the necessary "infrastructure":
public class DisposableCollectionWrapper<D> : IDisposable where D : IDisposable { private readonly IEnumerable<D> _disposables; public DisposableCollectionWrapper(IEnumerable<D> disposables) { _disposables = disposables; } public void Dispose() { if (_disposables == null) return; foreach (var disposable in _disposables) { disposable.Dispose(); } } } public static class CollectionExtensions { public static IDisposable AsDisposable<D>(this IEnumerable<D> self) where D : IDisposable { return new DisposableCollectionWrapper<D>(self); } }
Also note that this is not the same as the situation described in C ++. In C ++, if you do not delete your object, you have a real memory leak. In C #, if you do not destroy your object, the garbage collector eventually starts and clears it.
Jordรฃo
source share