Files
Common-VS2019/SacsStandardBase/Base/Core/DisposableCollection.cs
T

79 lines
2.0 KiB
C#

using Sarand.Net.Standard.Base.App;
using Sarand.Net.Standard.Base.Utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Text;
namespace Sarand.Net.Standard.Base.Core
{
//=======================================================================
public sealed class DisposableCollection<T> : Collection<T>, IDisposable
where T : class, IDisposable
{
//-------------------------------------------------------------------
// Construction.
public DisposableCollection() : base() { }
public DisposableCollection(IList<T> items) : base(items) { }
public void Dispose()
{
while (this.Count > 0)
{
// Extract the first item from the list.
T item = this[0];
RemoveAt(0);
try
{
if (item != null)
item.Dispose();
}
catch (Exception exc)
{
// Ignore exception.
if (SacsSystem.DebugMode)
{
SaLogger.Debug($"{SysUtil.Fn} {ExceptionUtil.GetErrorStateMessage(exc)}");
Debugger.Break();
}
}
}
}
//-------------------------------------------------------------------
/// <summary>
/// Add item to the list.
/// <para>Null items are ignored.</para>
/// </summary>
public new void Add(T item)
{
if (item != null && !Contains(item))
base.Add(item);
}
/// <summary>
/// Add list of items to the collection.
/// <para>Null items are ignored.</para>
/// <para>Items that can't be cast to the required object type cause a debug break.</para>
/// </summary>
public void AddRange<O>(List<O> items) where O : class, IDisposable
{
if (items != null && !items.IsEmpty())
{
foreach (O item in items)
{
if (item == null) continue;
T obj = item as T;
if (obj != null)
Add(obj);
else if (SacsSystem.DebugMode)
Debugger.Break();
}
}
}
//-------------------------------------------------------------------
}
//=======================================================================
}