开发者

How to dispose a list of disposable objects?

开发者 https://www.devze.com 2023-01-08 07:34 出处:网络
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.

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 Di开发者_高级运维spose(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


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


Who creates the objects inside the list? i.e. who is responsible for their life-cycle? If MyDisposable creates them, then it is its responsibility to dispose of them. If someone else creates them, disposing of them can leave them with a reference to a useless object.


Yes, you need to dispose each of these objects explicitly, exactly the way you're doing it now.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号