Search code examples
.netvb.netidisposable

How to dispose a list of disposable objects?


I am implementing IDisposable for a class and while disposing there is a internal list of disposable objects. Should I be disposing those object by looping through them.

public Class MyDisposable 
     Implements IDisposable 
     private _disposbaleObjects as new List(of OtherDisposables)

     Public Overloads Sub Dispose() Implements System.IDisposable.Dispose
         Dispose(True)
         GC.SuppressFinalize(Me)
    End Sub

    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
        If Not Me.disposedValue Then
            If disposing Then
                  ? Should I dispose the the list like this ?
                  For Each obj In _disposbaleObjects
                      obj.dispose()
                  Next 
            End If               
        End If
        Me.disposedValue = True
    End Sub

End Class

Solution

  • Yes, iterate through the list and dispose each item.

    Also you can write an extension method:

    public static void Dispose(this IEnumerable<IDisposable> collection)
    {
        foreach (IDisposable item in collection)
        {
            if (item != null)
            {
                try
                {
                    item.Dispose();
                }
                catch (Exception)
                {
                    // log exception and continue
                }
            }
        }
    }
    

    and call it for your list

    coll.Dispose()
    

    Disposable collection, a collection that implements IDisposable:

    public sealed class DisposableCollection<T> : Collection<T>, IDisposable
        where T : IDisposable
    {
        public DisposableCollection(IList<T> items)
            : base(items)
        {
        }
    
        public void Dispose()
        {
            foreach (var item in this)
            {
                try
                {
                    item.Dispose();
                }
                catch
                {
                    // swallow
                }
            }
        }
    }
    

    Usage:

    using (var coll = new DisposableCollection(items))
    {
         // use
    }
    // it has been disposed